jQuery JS - 从 base64 代码中获取图像宽度和高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17774928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:56:23  来源:igfitidea点击:

JS - get image width and height from the base64 code

javascriptjqueryimagebase64dimensions

提问by bombastic

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

我有一个 base64 img 编码,你可以在这里找到。我怎样才能得到它的高度和宽度?

回答by gp.

var i = new Image(); 

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

i.src = imageData; 

回答by EscapeNetscape

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:

那么您可以使用 await 以同步编码样式获取数据:

var dimensions = await getImageDimensions(file)

回答by Bill Keller

I found that using .naturalWidthand .naturalHeighthad the best results.

我发现使用.naturalWidth.naturalHeight获得了最好的结果。

const img = new Image();

img.src = 'https://via.placeholder.com/350x150';

img.onload = function() {
  const imgWidth = img.naturalWidth;
  const imgHeight = img.naturalHeight;

  console.log('imgWidth: ', imgWidth);
  console.log('imgHeight: ', imgHeight);
};

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

这仅在现代浏览器中受支持。http://www.Hymanlmoore.com/notes/naturalwidth-and-naturalheight-in-ie/

回答by Desu

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

创建一个隐藏的<img>图像,然后使用 jquery .width() 和 . 高度()

$("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

在这里测试: 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

另一个没有按照 gp. 的 anser 添加到 dom 的小提琴: 这里