javascripthtmlcanvas

Result of html5 Canvas getImageData or toDataURL - Which takes up more memory?


Part of my app includes html5 photo editing using a mixture of standard 2d context canvases and webGL.

Anyway, I am saving 'undo' states while the user is manipulating their photo. These are all stored in a Javascript object as base64 image data.

Everything works fine and performance is good.

However I am wondering if storing the data from getImageData might take up less memory or offer better performance?

So to summarise my question is:

Which takes more space in memory, a base64 jpeg generated by toDataURL() or the result of getImageData()? And are there any performance differences between the two (with regards to loading onto a canvas, and pulling the data off of a canvas)

Thanks in advance.


Solution

  • Good question! I'm not sure about the true sizes of the objects themselves, and it should differ between implementions of JS, but that doesn't mean we can't make some educated guesses.

    First we can use the approximation function from this question: JavaScript object size

    And make an example: http://jsfiddle.net/g39uz/

    The string is perhaps 80116 bytes, compared to the ImageData's 720056 bytes. Or thereabouts.

    There's an order of magnitude difference here, and the difference would be even more stark if the image was simple. It's worth remembering that the Base64 representation can be compressed (and it is). Let's take it to the limit for a moment to see, by using a blank canvas:

    http://jsfiddle.net/g39uz/2/

    On a blank canvas the dataURL string is just 1996 bytes (or thereabouts) but the image data, which of course still dutifully describes every single pixel in painstaking array detail, is still 720056.

    In short, if you're storing it, the base64 string probably takes up less space. By an order of magnitude.