Note that there are some explanatory texts on larger screens.

plurals
  1. POReturning file size of canvas toDataUrl() using atob()
    text
    copied!<p>I am trying to load an image into a canvas from a URL and then get the dataUrl and use this to find out the size of an image.</p> <p>The result is that the image is shown to be a lot larger than it should be. </p> <p>For example, loading in a 60kb image results in the decoded variable returning it to be 134kb.</p> <p>When I run the same code on an image stored locally on my pc, getting the file object from a file input instead and the returned value is correct ( for example 60kb ).</p> <p>This is the code that I am using:</p> <pre><code> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var img = '/anImage.jpg'; var image = document.createElement('img'); image.src = img; ctx.drawImage(image, 500, 500); ctx.drawImage(image, img.width, img.height); var dataUrl = canvas.toDataURL('image/jpeg'); var d = dataUrl.substr(dataUrl.indexOf('base64,') + 7); var decoded = atob(d); var size = decoded.length; </code></pre> <p>I have tried using the dataUrl to output the image again and saving it... which still results in the image being 134kb and not the original size of 60Kb.</p> <p>I understand that base64 encoding makes an image 1.37 or so times bigger but the value is correct when getting the image object from a file input.</p> <p>I am not sure whether the compression level is being lost? Or whether I can somehow get this from the file object and then use it to set the second param for the toDataUrl() function?</p> <p>I cannot find any information relating specifically to this online so any information would be appreciated :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload