Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 705
gordyr Avatar asked Aug 10 '12 06:08

gordyr


1 Answers

getImageData() takes more memory than toDataURL()

  • ImageData is pixel array, the largest information about image, the length of pixel array is widthOfImage * heightOfImage * 4, for example imageData length of image with dimensions 100 is var imageDataArrayLenth = 100 * 100 * 4 = 40 000 (bytes);
  • BLOB (JPG or PNG) is imageData compressed with jpg or png algorithm can be less sized by 10 or 20 times than imageData (depends on image content).
  • DataURL (BASE64) is imageData compressed to JPG or PNG, then converted to string, and this string is larger by 37% (info) than BLOB.

Conclusion: Better way is to use BLOB (info).

//Example of using blob with objectURL var canvas = document.getElementById("canvas");  canvas.toBlob((blob) => {   let img = new Image();   img.onload = () =>  URL.revokeObjectURL(img.src);  // no longer need to read the blob so it's revoked   img.src = URL.createObjectURL(blob);   document.body.appendChild(img); }); 
like image 147
Alex Nikulin Avatar answered Nov 22 '22 07:11

Alex Nikulin