Using Javascript to encode images as DataURL

The following example shows how to draw an image on an HTML 5 Canvas element and encode the image as data-url schema. Being able to convert images into string, opens some interesting possibilities. In browsers that support HTML5 local data storage you can optimize the performance of you site by loading images once and saving them as string in the local database.

Keep in mind that the conversion of an image into text is very costly. An 8 Kb image might become 74 Kb when converted into text. However, reducing the number of HTTP requests by loading resources from a local database is a desirable benefit.

After drawing the image on a Canvas element you can get the data-url by calling toDataURL(). This will return a base64 encoded string, similarly to what you could achieve using PHP or other server side languages. When using Javascript to accomplish this task, be aware that images must be hosted in the same domain of your script. If you try to load images hosted in a different domai, toDataURL() will throw a ‘Security error code: 1000‘.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
 * Converts image URLs to dataURL schema using Javascript only.
 *
 * @param {String} url Location of the image file
 * @param {Function} success Callback function that will handle successful responses. This function should take one parameter
 *                            <code>dataURL</code> which will be a type of <code>String</code>.
 * @param {Function} error Error handler.
 *
 * @example
 * var onSuccess = function(e){
 *  document.body.appendChild(e.image);
 *  alert(e.data);
 * };
 *
 * var onError = function(e){
 *  alert(e.message);
 * };
 *
 * getImageDataURL('myimage.png', onSuccess, onError);
 *
 */
function getImageDataURL(url, success, error) {
    var data, canvas, ctx;
    var img = new Image();
    img.onload = function(){
        // Create the canvas element.
        canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;
        // Get '2d' context and draw the image.
        ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        // Get canvas data URL
        try{
            data = canvas.toDataURL();
            success({image:img, data:data});
        }catch(e){
            error(e);
        }
    }
    // Load image URL.
    try{
        img.src = url;
    }catch(e){
        error(e);
    }
}
/**
 * Converts image URLs to dataURL schema using Javascript only.
 *
 * @param {String} url Location of the image file
 * @param {Function} success Callback function that will handle successful responses. This function should take one parameter
 *                            <code>dataURL</code> which will be a type of <code>String</code>.
 * @param {Function} error Error handler.
 *
 * @example
 * var onSuccess = function(e){
 * 	document.body.appendChild(e.image);
 * 	alert(e.data);
 * };
 *
 * var onError = function(e){
 * 	alert(e.message);
 * };
 *
 * getImageDataURL('myimage.png', onSuccess, onError);
 *
 */
function getImageDataURL(url, success, error) {
	var data, canvas, ctx;
	var img = new Image();
	img.onload = function(){
		// Create the canvas element.
	    canvas = document.createElement('canvas');
	    canvas.width = img.width;
	    canvas.height = img.height;
		// Get '2d' context and draw the image.
		ctx = canvas.getContext("2d");
	    ctx.drawImage(img, 0, 0);
		// Get canvas data URL
		try{
			data = canvas.toDataURL();
			success({image:img, data:data});
		}catch(e){
			error(e);
		}
	}
	// Load image URL.
	try{
		img.src = url;
	}catch(e){
		error(e);
	}
}