Tweeting Photos From Webcam

by joshwoldstad in Circuits > Linux

2075 Views, 6 Favorites, 0 Comments

Tweeting Photos From Webcam

54c2ca0a9d29c99524000062.jpeg

Now that we have a LAMP Server set-up, we can create web-projects! The first project we're going to make is a program that will automatically tweet a picture from our webcam when we press "Snap Photo".

Getting Started

mobile.png

Before we can do anything, we need to set-up a new Twitter App.

  1. If you don't have a Twitter account, go to twitter.com and sign up.
  2. Before you can make Twitter Apps, you need to link your mobile phone to your account.
    1. Log-in to Twitter and click your profile picture at the top-right corner
    2. Click "Settings" in the drop down menu.
    3. Go to the mobile option on the menu on the left-hand side, then fill out that mobile information (You'll get a confirmation text)

Getting Your Twitter App License

app.png

Now that we have a Twitter account set-up, we can create our Twitter App.

  1. Go to apps.twitter.com, and hit "create new app" in the top-right corner.
  2. Fill out all the information (the URL must have "http://" or "https://" included)
  3. Read through the Terms and Conditions and create your app.
  4. Now you should be the "main page" of your app, below your app title there should be a toolbar, go to "Permissions"
  5. Select the "Read and Write" option and then the "Update Settings". (This will allow our app to tweet and read tweets).
  6. Go to "Keys and Access Tokens", then regenerate the consumer tokens, and generate the access tokens.

We need these to tweets to our account. If you forget or lose the tokens, you can always go back to your Twitter Apps page to find them.

Get CodeBird

codebird.png

Twitter has a bunch of good libraries that help with development, we're going to use the CodeBird Library.

We need to go to CodeBird's github. Download "cacert.perm" and "codebird.php".

Save these in the Computer/var/www/html folder. (Make sure that these files are the correct type!)

Setting Up the Webcam

WP_20150126_003.jpg
box.png
code.png

Now that we have the twitter library we need, we can get to setting up our webcam. I used a Rosewill 1.3Mega Pixel Webcam (about $30). On the client-side of this project, we're going to use HTML and Javascript. Check out David Walsh's awesome blog, that's where I got the base code for the webcam portion of our project.

We get :

<p><*html><br><*head>
<*script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"><*/script>
<*/head>
<*body>
	<*video id="video" width="640" height="480" autoplay><*/video>
	<*button id="snap" class="sexyButton">Snap Photo<*/button>
	<*canvas id="canvas" width="640" height="480"><*/canvas></p><p>	<*script>
        // Put event listeners into place
		window.addEventListener("DOMContentLoaded", function() {
			// Grab elements, create settings, etc.
			var canvas = document.getElementById("canvas"),
				context = canvas.getContext("2d"),
				video = document.getElementById("video"),
				videoObj = { "video": true },
				errBack = function(error) {
					console.log("Video capture error: ", error.code); 
				};</p><p>			// Put video listeners into place
			if(navigator.getUserMedia) { // Standard
				navigator.getUserMedia(videoObj, function(stream) {
					video.src = stream;
					video.play();
				}, errBack);
			} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
				navigator.webkitGetUserMedia(videoObj, function(stream){
					video.src = window.webkitURL.createObjectURL(stream);
					video.play();
				}, errBack);
			} else if(navigator.mozGetUserMedia) { // WebKit-prefixed
				navigator.mozGetUserMedia(videoObj, function(stream){
					video.src = window.URL.createObjectURL(stream);
					video.play();
				}, errBack);
			}
			// Trigger photo take
			// Trigger photo take
			document.getElementById("snap").addEventListener("click", function() {
                context.drawImage(video, 0, 0, 640, 480);
            });
		}, false);
	<*/script>
<*/body>
<*/html></p>

This is the code that will allow us to take pictures with the webcam. (Be sure to remove all the *s, they're only here to keep the code from autoformatting)

This code is setting up listeners to the camera, then using draw image to write to the canvas. Save this as webcam.php.

Testing Out the Webcam

intern.png

Now that we have the webcam code, we can use the LAMP Server to test it out. Now plug-in your webcam and go to your favorite web-browser, then type in "localhost/webcam.php".

  1. localhost will ask if to use your camera. (Allow)
  2. If your internal webcam comes up, you can change it by clicking the film icon on the top-right corner and changing the "camera" option to the "USB camera" option. (You'll have to allow again)

You can press the "snap photo" button, and it will take a canvas image of the webcam!

Creating the PHP File

php.png

Our "webcam.php" communicates with the client, so we need something to communicate with the server-side of our project.

<?php
	require_once('codebird.php');

	\Codebird\Codebird::setConsumerKey("YOUR CONSUMER KEY", "YOUR CONSUMER SECRET");
	$cb = \Codebird\Codebird::getInstance();
	$cb->setToken("YOUR ACCESS TOKEN", "YOUR ACCESS SECRET");

	$img = $_POST['img'];
	$datetime = $_POST['date'];
	$img = str_replace('data:image/png;base64,', '', $img);
	$img = str_replace(' ', '', $img);
	$data = base64_decode($img);

	
	$file =  $datetime.'temp.png';
	$success = file_put_contents($file, $data);

	$media_files = array($file);

	$media_ids = array();

	foreach($media_files as $file)
	{
		$reply = $cb->media_upload(array('media' => $file));
	
		$media_ids[] = $reply->media_id_string;
	}
	
	$media_ids = implode(',', $media_ids);
	
	$reply = $cb->statuses_update(array(
		'status' => 'I\'m sending a tweet with a picture!',
		'media_ids' => $media_ids
	));
?>

So what is going on here? If we check it out step by step, it's not too difficult

  1. First, we require CodeBird, and put our Consumer and Access tokens, that way we can communicate with Twitter.
  2. Then, we assign $img to the data sent over by Ajax (this will be in webcam.php), and then manipulate it to format correctly with php.
  3. After the information has been encoded, we save it to our server, this allows Twitter to upload it.
  4. Next is code that allows us to upload multiple pictures up to Twitter (but for this project, we are only sending one). It takes the array, and formats the information to allow it to be tweeted.

If you want to change what the tweet says, go to the 'status' and modify as desired.

Save this as "pictweet.php' in the same folder we've been using. Now we're almost finished!

Connecting "webcam.php" and "pictweet.php"

ajax.png

Now all that is remaining is using AJAX to connect the two files, and then everything should be all working!

We have the client-side code and the server-side code, but they don't communicate with each other. Using AJAX, we can send information from the "webcam.php" to "pictweet.php".

Go to "webcam.php" and replace the following code block:

// Trigger photo take			
document.getElementById("snap").addEventListener("click", function() {
                context.drawImage(video, 0, 0, 640, 480);
            });
		}, false);

with

document.getElementById("snap").addEventListener("click", function() {

                context.drawImage(video, 0, 0, 640, 480);
                canvas = document.getElementById("canvas");
				var img = canvas.toDataURL("image/png");			console.log(img);
				var date = Date();
				$.ajax({
				  type: "POST",
				  url: "pictweet.php",
				  data: {img : img, date : date}
				});
            });

And save "webcam.php"!

Finishing Up

logo.png

Now that Ajax is in place, we're finished! To get this project to start tweeting, just go back to Step 5, and run "webcam.php" in your local host. If everything was set-up correctly, every time you press "Snap Photo" it will take a picture, then upload if to Twitter!