How to get file size of newly created Image() if src is base64 string?

陌路散爱 提交于 2020-12-02 07:24:08

问题


How can I get the size of the newly created new Image() in bytes if this image's src is base64 data image?

I have such coffeescript code:

# This string is received after some original image preprocessing
base64String = "data:image/jpeg;base64......"

newImageObj = new Image()
newImageObj.src = base64String
newImageObj.onload = ->
  console.log "Resized image width is " + this.width
  console.log "New file size in bytes is " + newImageObj.fileSize

The output is always like this:

Resized image width is 500
New file size in bytes is undefined

This newImageObj.fileSize is always undefined.


回答1:


here is the algorithm to find file size from base64 string:

base64String = "data:image/jpeg;base64......";

var stringLength = base64String.length - 'data:image/png;base64,'.length;

var sizeInBytes = 4 * Math.ceil((stringLength / 3))*0.5624896334383812;
var sizeInKb=sizeInBytes/1000;



回答2:


I'd personally use something like this to do the above, which will work correctly in the case that the data isn't formatted correctly (eg, an '=' missing, which usually gets decoded correctly anyway)

new Buffer(base64String, 'base64').length



回答3:


I'm a little late to the question here, and maybe I'm wrong but...

Looking at your code above, it looks like you are defining a function and using arrow notation to return the answer. However, there are TWO lines following the arrow, and they aren't grouped in any way, so... the arrow notation is returning the value of onload() to the first log() only. So "this" actually has a value. But the second log() is a new command altogether, right? It's not being returned from onload(). So newImageObj is undefined.

Or maybe it's a coffeescript syntax, I'm not familiar with it. Would this fix it?

newImageObj = new Image()
newImageObj.src = base64String
newImageObj.onload = ->
{
  console.log "Resized image width is " + this.width
  console.log "New file size in bytes is " + newImageObj.fileSize
}


来源:https://stackoverflow.com/questions/29939635/how-to-get-file-size-of-newly-created-image-if-src-is-base64-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!