appcropolois
  •  Templates
  • Builder
    •  Product Tour
    •  Sign up
    •  Dashboard
  •  Learn
  •  Discover
  •  Upgrade
  •  Sign in
  •  My Profile
    • View Orders
    • Edit Profile
    • Sign Out
  •  Cart
    ➜ 
  1. Home
  2. Learn
  3. Using Javascript to encode ...
Share

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);
	}
}

 

By: Raul Sanchez
Categories: Blog, Web Technology
Posted on: Tuesday, February 28, 2012

Sign in to post your comment


Not registered? Create an Account.

Lost your password? Click here to recover.

21 comment


xiangchao027
xiangchao027 Thursday 10th, January 2013 - 02:54:23 PM

It's a excellent way to encode the image to be a string, but it gets more space to store the images data, why don't you just use the C# or java to transmit the image files to other forms to store? And canvas element doesn't have whole support till now.

sanraul
sanraul Saturday 12th, January 2013 - 12:07:58 AM

That's a very good point. However, the purpose of this article is to show how to leverage the capability (DataURL), in HTML/Canvas. Thanks for the feedback.

URL
URL Saturday 27th, May 2017 - 01:35:33 AM

... [Trackback] [...] Read More here: appcropolis.com/blog/web-technology/javascript-encode-images-dataurl/ [...]

writeessay
writeessay Wednesday 4th, April 2018 - 06:14:25 PM

write a paper for me http://sertyumnt.com/ I have observed that in the world these days, video games are the latest trend with kids of all ages. Many times it may be impossible to drag your kids away from the games. If you want the very best of both worlds, there are plenty of educational activ…

essayforme
essayforme Thursday 12th, April 2018 - 06:03:15 AM

write essay for me http://dekrtyuijg.com/ Cheers. Loads of knowledge!

Google
Google Friday 10th, August 2018 - 07:53:57 PM

Google The details talked about inside the article are a few of the best available.

Google
Google Monday 29th, October 2018 - 05:28:18 PM

Google We came across a cool web-site that you could get pleasure from. Take a look in case you want.

Google
Google Friday 15th, March 2019 - 12:55:12 AM

Google Every after in a when we decide on blogs that we study. Listed beneath would be the newest web sites that we choose.

Google
Google Sunday 17th, March 2019 - 03:39:28 PM

Google The data mentioned within the article are some of the most effective accessible.

Google
Google Monday 29th, April 2019 - 01:55:58 PM

Google That will be the end of this write-up. Here you will obtain some internet sites that we feel you’ll enjoy, just click the hyperlinks.

javascript - получить обрезанное изображение для отображения на новом холсте - Переполнение стека
javascript - получить обрезанное изображение для отображения на новом холсте - Переполнение стека Sunday 2nd, June 2019 - 01:22:07 PM

[…] сериализовать изображение в URI данных. В этом блоге есть учебник . Это создаст строку, которую вы можете хранить в […]

How to save an image to localStorage and display it on the next page? – inneka.com
How to save an image to localStorage and display it on the next page? – inneka.com Tuesday 2nd, July 2019 - 07:32:46 PM

[…] could serialize the image into a Data URI. There’s a tutorial in this blog post. That will produce a string you can store in local storage. Then on the next page, use the data uri […]

Phonegap – Save image from url into device photo gallery – inneka.com
Phonegap – Save image from url into device photo gallery – inneka.com Saturday 6th, July 2019 - 08:06:22 AM

[…] plugin Canvas2ImagePlugin. Install it and add the following function to your code which is based on getImageDataURL() by Raul Sanchez […]

Maha Pharma
Maha Pharma Tuesday 20th, August 2019 - 05:27:43 PM

[…] Maha Pharma Maha Pharma Maha Pharma Maha Pharma Maha Pharma Maha Pharma Maha Pharma Maha Pharma Maha Pharma Maha Pharma Maha Pharma Maha Pharma Maha Pharma Maha Pharma Maha Pharma Maha Pharma Maha Pharma […]

Phonegap-将图片从url保存到设备照片库中 – 玩编程
Phonegap-将图片从url保存到设备照片库中 – 玩编程 Thursday 16th, January 2020 - 07:49:41 PM

[…] 另一种简单的方法是使用Cordova / Phonegap插件Canvas2ImagePlugin。安装它,并将以下函数添加到基于Raul Sanchez的getImageDataURL()的代码中(谢谢!)。 […]

javascript – How to save an image to localStorage and display it on the next page?-ThrowExceptions – ThrowExceptions
javascript – How to save an image to localStorage and display it on the next page?-ThrowExceptions – ThrowExceptions Saturday 7th, March 2020 - 08:15:48 PM

[…] could serialize the image into a Data URI. There’s a tutorial in this blog post. That will produce a string you can store in local storage. Then on the next page, use the data uri […]

javascript – Phonegap – Save image from url into device photo gallery-ThrowExceptions – ThrowExceptions
javascript – Phonegap – Save image from url into device photo gallery-ThrowExceptions – ThrowExceptions Friday 15th, May 2020 - 02:33:46 PM

[…] plugin Canvas2ImagePlugin. Install it and add the following function to your code which is based on getImageDataURL() by Raul Sanchez […]

如何将映像保存到localStorage并将其显示在下一页上?_javascript问答
如何将映像保存到localStorage并将其显示在下一页上?_javascript问答 Sunday 1st, November 2020 - 11:56:29 PM

[…] 您可以将图像序列化为数据URI。这篇博客文章中有一个教程。这将产生一个可以存储在本地存储中的字符串。然后在下一页上,使用数据uri作为图像源。 […]

如何将映像保存到localStorage并将其显示在下一页上?|jquery问答
如何将映像保存到localStorage并将其显示在下一页上?|jquery问答 Wednesday 11th, November 2020 - 02:32:32 PM

[…] 您可以将图像序列化为数据URI。这篇博客文章中有一个教程。这将产生一个可以存储在本地存储中的字符串。然后在下一页上,使用数据uri作为图像源。 […]

Google
Google Sunday 20th, December 2020 - 08:23:37 PM

Google Usually posts some very interesting stuff like this. If you’re new to this site.

Google
Google Saturday 2nd, January 2021 - 10:19:44 PM

Google Please visit the web sites we follow, including this one particular, as it represents our picks in the web.

Building Apps?

Create, customize, and publish mobile web applications using the Appcropolis Mobile Builder.

Get Started
Browse Categories
  • Books (0)
  • CSS3 (2)
  • Design (0)
  • Frameworks (10)
  • How-To (6)
  • HTML5 (2)
  • jQuery Mobile (7)
  • Miscelaneous (1862)
  • Mobile Builder (1)
  • News (9)
  • Opinion (1)
  • User Experience (0)
  • Web Technology (11)
  • Webclips (4)

Ready-to-use Templates

Check out Appcropolis Mobile Templates

We offer 1,000's of mobile templates that are fully designed, coded, and ready to use. Learn more.

Download Free Templates

Contact Us

Your feedback means the world to us.
Contact us if you have any questions or
any feature requests:

Saint Louis, MO 63101
911 Washington Ave
Email: info@appcropolis.com

Appcropolis

  •   About Us
  •   Blog
  •   Discover
  •   Templates
  •   Contact Us

Get Free Templates

Subscribe to our newsletter to receive
notification about new templates, prodcut updates,
and technical articles.


© 2025 Appcropolis, LLC · All Rights Reserved
Sitemap  ·  Terms Of Service  ·  Privacy