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); } }
Not registered? Create an Account.
Lost your password? Click here to recover.
Create, customize, and publish mobile web applications using the Appcropolis Mobile Builder.
Get StartedWe offer 1,000's of mobile templates that are fully designed, coded, and ready to use. Learn more.
Download Free Templates
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.
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.
... [Trackback] [...] Read More here: appcropolis.com/blog/web-technology/javascript-encode-images-dataurl/ [...]
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…
write essay for me http://dekrtyuijg.com/ Cheers. Loads of knowledge!
Google The details talked about inside the article are a few of the best available.
Google We came across a cool web-site that you could get pleasure from. Take a look in case you want.
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 The data mentioned within the article are some of the most effective accessible.
Google That will be the end of this write-up. Here you will obtain some internet sites that we feel youll enjoy, just click the hyperlinks.
[…] сериализовать изображение в URI данных. В этом блоге есть учебник . Это создаст строку, которую вы можете хранить в […]
[…] 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 […]
[…] plugin Canvas2ImagePlugin. Install it and add the following function to your code which is based on getImageDataURL() by Raul Sanchez […]
[…] 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 […]
[…] 另一种简单的方法是使用Cordova / Phonegap插件Canvas2ImagePlugin。安装它,并将以下函数添加到基于Raul Sanchez的getImageDataURL()的代码中(谢谢!)。 […]
[…] 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 […]
[…] plugin Canvas2ImagePlugin. Install it and add the following function to your code which is based on getImageDataURL() by Raul Sanchez […]
[…] 您可以将图像序列化为数据URI。这篇博客文章中有一个教程。这将产生一个可以存储在本地存储中的字符串。然后在下一页上,使用数据uri作为图像源。 […]
[…] 您可以将图像序列化为数据URI。这篇博客文章中有一个教程。这将产生一个可以存储在本地存储中的字符串。然后在下一页上,使用数据uri作为图像源。 […]
Google Usually posts some very interesting stuff like this. If youre new to this site.
Google Please visit the web sites we follow, including this one particular, as it represents our picks in the web.