Taking Webcam Photos Via the Command Line


2014-02-18

Here's an easy way to use your default webcam to take a photo with a single command from a terminal:

mplayer -vo png -frames 1 tv://

I wanted a quick and easy way to take a photo with my laptop's webcam and upload it to my server on a regular basis when I'm away from my machine. Side note: this wasn't to take photos of unknowing human victims, but to check in on my dogs :).

I realized that the first few frames weren't great due to the camera turning on, so I had it take 5 frames:

mplayer -vo png -frames 5 tv://

I then wanted to upload them to my server to be accessible (behind nginx's basic authentication so only those with the credentials can see them):

mplayer -vo png -frames 5 tv://; \
scp 00000005.png magnatecha.com:~/webroot/mydomain.com/cam/pic.png;

I also wanted to take the webcam photo on an interval:

while true; do \
mplayer -vo png -frames 5 tv://; \
scp 00000005.png magnatecha.com:~/webroot/mydomain.com/cam/pic.png; \
sleep 120; \ 
done;

That creates an infinite loop that takes 5 frames of photos, uploads the fifth one to my server, waits 120 seconds and then does it all again. This allows me to see a photo of whatever my laptop is pointed at that is at most 2 minutes old.