JavaScript Canvas Image Conversion
At last week's Mozilla WebDev Offsite, we all spent half of the last day hacking on our future Mozilla Marketplace app. One mobile app that recently got a lot of attention was Instagram, which sold to Facebook for the bat shit crazy price of one billion dollars. Since I wouldn't mind having a bill in my back account, I decided to create an Instagram-style app (which I'll share with you in the future). This post details how you can convert an image to canvas and convert a canvas back to an image.
Convert an Image to Canvas with JavaScript
To convert an image to canvas, you use a canvas element's context's drawImage
method:
// Converts image to canvas; returns new canvas element function convertImageToCanvas(image) { var canvas = document.createElement("canvas"); canvas.width = image.width; canvas.height = image.height; canvas.getContext("2d").drawImage(image, 0, 0); return canvas; }
The 0, 0
arguments map to coordinates on the canvas where the image data should be placed.
Convert Canvas to an Image with JavaScript
Assuming modifications to the image have been made, you can easily convert the canvas data to image data with the following snippet:
// Converts canvas to an image function convertCanvasToImage(canvas) { var image = new Image(); image.src = canvas.toDataURL("image/png"); return image; }
The code above magically converts the canvas to a PNG data URI!
Alas, converting an image to canvas and canvas to an image is probably much easier than you think. In future posts, I'll detail how you can apply different image filters to your canvased image. In the mean time, start buying fancy cars and houses with the future billion you'll have!
convertCanvasToImage should have a callback parameter, because the data set as image src takes some time to load. So the returned image may be blank. ;o)
Better handling:
cannot we just convert image jpg into png without using canvas??
It is still blank. I need to type the function name again to get data url.
Demo (clear the cache! ;o)):
http://sunbox.github.com/image-to-canvas-to-image/
Cool Stuff David! I have been playing with canvas a few months ago and using similar code code to your example I’ve created a javascript image compression tool that works pretty well.
The cool thing about it is that you can compress images on the client side before uploading :)
You can check out the demo at http://makeitsolutions.com/labs/jic/
Checked out your solution, but couldnt get how you ‘compress’ it? All I can see is, you take the image quality between 0 & 1 and use that on toDataURL() and return the resulting object. There isnt any special compress or am i missing something?
I have created a plugin in jquery which will easily convert images to canvas, and let you download the current image lying on canvas.
Generally outputting canvas to image gives ImageData ( base64 ), i have used a little php script that will give a direct download option to user.
http://thetutlage.com/post=TUT213
In function convertImageToCanvas(image) where does ‘image’ come from?
The image is a reference to an image node within the page.
I am developing a Phonegap app for Android and in Android, toDataUrl() method is supported in 3.2+ versions. My intention is to get a cropped image in .png or .jpeg format and send that cropped image to server. Please guide me doing this.
How can I send a Image to the sever and save it in the sever using php?
You’d do an AJAX POST to the server and save the data to file.
How can i rotate before convert canvas to image?
Can i use this to resize images for retina resolution??
Hello Guys,
What should be different if I need to convert from png to canvas and canvas to jpg?
Hi Guys,
What should be different if I need to convert from png to canvas and canvas to jpg
Worth noting that this could fail if your image isn’t from the same domain. Check out https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image for details on how to safely work past cross-origin canvas tainting.
I want to convert div contents in to image and save in a folder ????? any one have idea?…….
Great, thanks for the example. It works awesomely.
Hai,
What is the advantage of converting an image to canvas? Does it decrease the size of picture(or in terms of loading time)…………?
No, I think the idea is to convert the image to canvas so you can apply effects to it using javascript.
When I press “snap photo” it takes the photo and it then reloads the page, any thoughts.Code as I have it (on an aspx page with nothing else on it)
https://gist.github.com/ghirst/7370961
same problem in here, did you solve it?
easy solution here is that the form your code is wrapped in sees the snap button as a submit button. add type=’button’ to your snap button and the form will no longer submit onclick
Hi,
Are you able to convert a Java Script code to jpeg file? I have 6 image banners from the forex company that I am an affiliate with. I have the Landing page URL which I made the tiny URL and the original java script code. I need to convert it to jpeg to upload the image for facebook ad campaign. How do I go about it?
Are you also able to resize it to 600 pixels wide by 225 pixels tall with high resolution as required by facebook to place ad on their news feed and make sure that the original Java Script Code remain the same so it will track to my campaign ID with the forex company.
Let me know if you are able to help me. Much appreciated!
Thanks a lot!
Mrityunjay
Hi David,
How does this code behave with IE10/IE11, where I am loading image from other domain, let say I have angular application, I am loading Image via web server call.
toDataURL()
is not working incase of cross domain images, throwing security exception in IE10/IE11. Can you please suggest any solution for this.Shravan
You really wrote a nice guide for this effect.
But for me, as newcomer, I’m would like to ask:
Why, do they convert the pictures to Canvas elements?
kind regard
because if you directly apply the filter or any other change on the image you can’t download the effected image. so you first convert it into the canvas and apply filters on canvas then you cant convert the canvas to image that can be downloadable. Understood
Hi
I need to convert Div content to image … Can you guide me how it can be done …. a sample code will help even better ..
Thanks
Hey ! Thanks for this post !
By the way, it seems canvas to image is no longer secure, or at least, it have been restricted.
I try to convert a canvas to a PNG image, and I’ve got :
Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
With further researches, I found this stackoverflow question : http://stackoverflow.com/questions/20424279/canvas-todataurl-securityerror That mention
For example, you can no longer use the canvas toBlob(), toDataURL(), or getImageData() methods; doing so will throw a security error.
Is there a way to go beyond those security errors .. ? Or any fix/solutions to it ?
Thanks by advance !
Lucas.
I’m facing the same problem… Have you figured this out? tks
Amazing!
Hello Milind,
How does this work if we have to fetch images which are not from the same URL. I mean you are getting a JSON feed of image URL’s which are from different domains. Also, your script leverages local storage, how would you go about the same if local storage is not available.
Vish
Geoff try ur code again without the html form tag
Hello,
I have brpblem in Safari like this
http://demo.phpkungfu.club/image.html
Chrome, Firefox is OK, but safari, IE is error
Please help me fix its
Son
Hi David,
This works for me, the problem is that I am trying to convert the D3 graph to PNG inorder to create a PDF file using PhantomJS.
PhantomJS I know is no longer being developed and maintained it has one bug that it can not render inline SVG images. So using your solution I am converting the SVG to PNG and using that PNG to generate the PDF.
It works but the image of the graph is blurry as it is not scaled nicely as a SVG image. Can you suggest an solution for the same ?
Hey David, i need to convert a drawn image
{x = canvas.drawImage(blah blah blah)}
from png to jpg with JavaScript. Thanks in advance.I have a png image converted to canvas. Now, I want to be able to select some text on the canvas when I double click on it. How do I do that?