繁体   English   中英

JS - 从base64代码中获取图片的宽高

[英]JS - get image width and height from the base64 code

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

var i = new Image(); 

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

i.src = imageData; 

对于同步使用,只需将其包装成这样的承诺:

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

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

var dimensions = await getImageDimensions(file)

我发现使用.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); };

文件:

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

使用该图像创建一个隐藏的<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);

在这里测试:小提琴

最初创建的图像不是隐藏的。 它被创建,然后你得到宽度和高度,然后将其删除。 这可能会导致大图像中的可见性非常短,在这种情况下,您必须将图像包装在另一个容器中,并使该容器隐藏而不是图像本身。


根据 gp. 的分析器,另一个没有添加到 dom 的小提琴:这里

更现代的解决方案是使用HTMLImageElement.decode()而不是onload事件。 decode()返回一个承诺,因此可以与await同步使用。

异步使用:

let img = new Image();
img.src = "myImage.png";
img.decode().then(() => {
    let width = img.width;
    let height = img.height;
    // Do something with dimensions
});

同步使用(在 async 函数内部):

let img = new Image();
img.src = "myImage.png";
await img.decode();
let width = img.width;
let height = img.height;
// Do something with dimensions

暂无
暂无

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

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