简体   繁体   English

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

[英]How to find the base64 image width and height

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. 请帮助如何获得图像的原始宽度和高度。

You can build another image element and get its size : 您可以构建另一个图像元素并获取其大小:

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

The Image() constructor for HTMLImageElements mentioned in dystroy's answer is the right way to go, but there's a caveat: The constructor is actually asynchronous! 在dystroy的答案中提到的HTMLImageElements的Image()构造函数是正确的方法,但有一点需要注意:构造函数实际上是异步的! 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. 根据我的有限实验,dystroy的代码将在Chrome中100%有效,但有时仅在Firefox和Safari中有效。 Don't know about others. 不了解别人。

The right way to do it seems to be with an onload handler , as in: 正确的方法似乎是使用onload处理程序 ,如:

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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM