Showing posts with label data URI. Show all posts
Showing posts with label data URI. Show all posts

Sunday, August 4, 2013

Image Data URIs with JavaScript

<img src="your_image.png" id="myimage" />
<canvas width="300" height="300" id="mycanvas" style="display: none;"></canvas>


You will need to create a canvas element with the correct dimensions and copy the image data with thedrawImage function. Then you can use the toDataURL function to get a data: url that has the base-64 encoded image. Note that the image must be fully loaded, or you'll just get back an empty (black, transparent) image.
It would be something like this. I've never written a Greasemonkey script, so you might need to adjust the code to run in that environment.
function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    var dataURL = canvas.toDataURL();

    return dataURL;
}
var myImage = document.getElementById('myimage');
var imageData = getbase64Image(myImage);
Return like something: "data:image/png;base64,BASE_64_IMAGE_DATA"; 

Image Data URIs with PHP

If you troll page markup like me, you've no doubt seen the use of data URI's within image src attributes. Instead of providing a traditional address to the image, the image file data is base64-encoded and stuffed within the src attribute. Doing so saves a network request for each image, and if you're the paranoid type, can prevent exposure of directory paths. Since creating data URIs is incredibly easy, let me show you how to do it with PHP.

The PHP

Start by reading in the image using file_get_contents (or any other PHP method you'd like), then convert the image to base64 using base64_encode:
// A few settings
$image = 'cricci.jpg';

// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;

// Echo out a sample image
echo '<img src="',$src,'">';
With the image data in base64 format, the last step is placing that data within the data URI format, including the image's MIME type. This would make for a good function:
function getDataURI($image, $mime = '') {
	return 'data: '.(function_exists('mime_content_type') ? mime_content_type($image) : $mime).';base64,'.base64_encode(file_get_contents($image));
}
The thing to remember is that IE7 and lower don't support data URIs, so keep that in mind if you're considering switching from image paths to data URIs!

http://davidwalsh.name/data-uri-php