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

后端 未结 3 740
一向
一向 2020-12-24 14:10

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 manipula

3条回答
  •  误落风尘
    2020-12-24 14:48

    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);
    });
    

提交回复
热议问题