JavaScript Canvas Image Conversion

By  on  

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!

Recent Features

Incredible Demos

  • By
    Checkbox Filtering Using MooTools ElementFilter

    When I first wrote MooTools ElementFilter, I didn't think much of it. Fast forward eight months later and I've realized I've used the plugin a billion times. Hell, even one of the "big 3" search engines is using it for their maps application.

  • By
    MooTools-Like Element Creation in jQuery

    I really dislike jQuery's element creation syntax. It's basically the same as typing out HTML but within a JavaScript string...ugly! Luckily Basil Goldman has created a jQuery plugin that allows you to create elements using MooTools-like syntax. Standard jQuery Element Creation Looks exactly like writing out...

Discussion

  1. 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:

    // Converts canvas to an image
    function convertCanvasToImage(canvas, callback) {
      var image = new Image();
      image.onload = function(){
        callback(image);
      }
      image.src = canvas.toDataURL("image/png");
    }
    
    • test

      cannot we just convert image jpg into png without using canvas??

    • Rohn

      It is still blank. I need to type the function name again to get data url.

  2. 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/

    • Varun

      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?

  3. 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

  4. Kevin

    In function convertImageToCanvas(image) where does ‘image’ come from?

    • The image is a reference to an image node within the page.

  5. Ashwini

    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.

  6. roscky

    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.

  7. Crail

    How can i rotate before convert canvas to image?

  8. Nisanth

    Can i use this to resize images for retina resolution??

  9. amaro

    Hello Guys,

    What should be different if I need to convert from png to canvas and canvas to jpg?

  10. Hi Guys,

    What should be different if I need to convert from png to canvas and canvas to jpg

  11. 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.

  12. Anand

    I want to convert div contents in to image and save in a folder ????? any one have idea?…….

  13. Mat

    Great, thanks for the example. It works awesomely.

  14. Aslam

    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.

  15. 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

    • César

      same problem in here, did you solve it?

    • Eefacsen

      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

  16. 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

  17. 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

  18. 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

    • Aftab

      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

  19. Prasanna

    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

  20. 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.

    • Viny Machado

      I’m facing the same problem… Have you figured this out? tks

    • Jamiel Sharief
      function convertCanvasToImage(canvas) {
      	var image = new Image();
      	image.src = canvas.toDataURL("image/png");
              img.crossOrigin = "anonymous";	
      	return image;
      }
      
  21. Eric

    Amazing!

  22. Vish

    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

  23. czar

    Geoff try ur code again without the html form tag

  24. 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

  25. Subhadip Pal

    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 ?

  26. Bolu

    Hey David, i need to convert a drawn image {x = canvas.drawImage(blah blah blah)} from png to jpg with JavaScript. Thanks in advance.

  27. Amruta

    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?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!