Image/Video Manipulation

Images or or frames of video that are drawn onto a Canvas can be manipulated, pixel by pixel.

Assuming you have a canvas with video or an image drawn to it, here is an example:

// Get at pixel data			
var imageData = thecontext.getImageData(0, 0, 640, 480);

// iterate over all pixels
for(var i = 0, n = imageData.data.length; i < n; i += 4) {
	
	// Get existing pixel data
	var red = imageData.data[i];
	var green = imageData.data[i + 1];
	var blue = imageData.data[i + 2];
	var alpha = imageData.data[i + 3];

	// Set new pixel data
	imageData.data[i + 1] = red;
	imageData.data[i + 2] = red;
	imageData.data[i + 3] = red;
}
thecontext.putImageData(imageData, 0, 0);			
			
Example

Writing Files with Node.js

So far, we have been keeping files and other data off of the server and just using the server to store things in memory or sending directly out to clients. There are a plethora of reasons that we might need to capture and save data as it comes through a Socket.

To write a file with Node.js, we use the File System module: fs, in particular the fs.writeFile(filename, data, [options], callback) method:

var fs = require('fs');

fs.writeFile('message.txt', 'Hello Node', function (err) {
  if (err) throw err;
  console.log('It\'s saved!');
});

To write binary data we need to go a step further. Here is what a Data URL for an image looks like when coming from the browser:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAATUAAAGhCAIAAACPirQGAAAPUWlDQ1BJQ0MgUHJvZmlsZQAAeAGtWHk4lF3/P7MbYxkaa2hCdrIv2ZfIvu9kHYxljLFkya6kRSgKUSHJUioqsiRSChVlaSFLkaQQJdt7D0/Pc72/3/Ve7z/vmWvO+ZzP+W73+c7c3/vcALDxeVGpwXAAQAglgmZjpEd0cnYhYt4AGPRhAfxAxssnnKprZWUGifyHtjwAyUKtX5pui3HG029Mr7qcUClmEZjTTvkPSn9oFhrkEACYFEQQ/Le
to save it, we need to cut off the "data:image/jpeg;base64," portion, create a "buffer" with the right type and then write it out. The below example works for JPEG images:
// Saving a data URL (server side)
var searchFor = "data:image/jpeg;base64,";
var strippedImage = data.slice(data.indexOf(searchFor) + searchFor.length);
var binaryImage = new Buffer(strippedImage, 'base64');
fs.writeFileSync(__dirname + '/theimage.jpg', binaryImage);