JS - get image width and height from the base64 code

浪子不回头ぞ 提交于 2019-11-26 09:00:28

问题


I have a base64 img encoded that you can find here. How can I get the height and the width of it?


回答1:


var i = new Image(); 

i.onload = function(){
 alert( i.width+", "+i.height );
};

i.src = imageData; 



回答2:


For synchronous use just wrap it into a promise like this:

function getImageDimensions(file) {
  return new Promise (function (resolved, rejected) {
    var i = new Image()
    i.onload = function(){
      resolved({w: i.width, h: i.height})
    };
    i.src = file
  })
}

then you can use await to get the data in synchronous coding style:

var dimensions = await getImageDimensions(file)



回答3:


I found that using .naturalWidth and .naturalHeight had the best results.

var img = new Image();

img.onload = function() {
    var imgWidth = img.naturalWidth,
        imgHeight = img.naturalHeight;
};

This is only supported in modern browsers. http://www.jacklmoore.com/notes/naturalwidth-and-naturalheight-in-ie/




回答4:


Create a hidden <img> with that image and then use jquery .width() and . height()

$("body").append("<img id='hiddenImage' src='"+imageData+"' />");
var width = $('#hiddenImage').width();
var height = $('#hiddenImage').height();
$('#hiddenImage').remove();
alert("width:"+width+" height:"+height);

Test here: FIDDLE

Image is not initially created hidden. it gets created, then you get width and height and then remove it. This may cause a very short visibility in large images in this case you have to wrap the image in another container and make that container hidden not the image itself.


Another Fiddle that does not add to dom as per gp.'s anser : HERE



来源:https://stackoverflow.com/questions/17774928/js-get-image-width-and-height-from-the-base64-code

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