javascript 如何找到base64图像的宽度和高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14274822/
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-10-26 21:11:51  来源:igfitidea点击:

How to find the base64 image width and height

javascriptjqueryhtml

提问by vvr02

How to find the base64 image width and height

如何找到base64图像的宽度和高度

<img id="thumb0" width="200" height="200" 
src="data:image/png;base64, ................">

Image property width and height are constant as i need to show them as thumb nail, but where as the original image properties are different.

图像属性宽度和高度是恒定的,因为我需要将它们显示为缩略图,但原始图像属性不同。

I need to get the original image height and width.

我需要获取原始图像的高度和宽度。

Suppose my original image height and width are 750 X 500

假设我的原始图像高度和宽度是750 X 500

I tried like this but getting the property width and height

我试过这样但得到属性宽度和高度

$("#thumb0").width();

value is 200.

值为200

Please help how to get orginal width and height of the image.

请帮助如何获取图像的原始宽度和高度。

回答by Denys Séguret

You can build another image element and get its size :

您可以构建另一个图像元素并获取其大小:

var img = new Image();
img.src = $('#thumb0').attr('src');
var originalWidth = img.width;

回答by ycz6

The Image() constructor for HTMLImageElementsmentioned in dystroy's answer is the right way to go, but there's a caveat: The constructor is actually asynchronous! As a result, you may experience unexpected behavior in certain browsers; from my limited experiments, dystroy's code will work 100% of the time in Chrome, but only sometimes in Firefox and Safari. Don't know about others.

图片()构造函数HTMLImageElements在dystroy的答复中提到是正确的道路要走,但有一点需要注意:构造函数实际上是异步的!因此,您可能会在某些浏览器中遇到意外行为;从我有限的实验来看,dystroy 的代码在 Chrome 中可以 100% 运行,但有时在 Firefox 和 Safari 中可以运行。不知道别人怎么样。

The right way to do it seems to be with an onload handler, as in:

正确的做法似乎是使用 onload handler,如下所示:

var img = new Image();
img.src = some_base64_image_source;
console.log(img.width);       // This might print out 0!
img.onload = function() {
    console.log(img.width);   // This will print out the width.
}