jquery 从JavaScript中的Base64代码获取图像宽度和高度

5cnsuln7  于 2023-02-03  发布在  jQuery
关注(0)|答案(5)|浏览(187)

我有一个Base64编码的图像,你可以找到here。我怎么才能得到它的高度和宽度?

omhiaaxx

omhiaaxx1#

var i = new Image();

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

i.src = imageData;
5us2dqdw

5us2dqdw2#

对于同步使用,只需将其 Package 成如下的promise:

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

uxh89sit3#

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

文件:

    • 一个月一次 *
    • 一个月一次 *

只有现代浏览器才支持此功能。* NaturalWidth and NaturalHeight in IE *

qxsslcnc

qxsslcnc4#

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

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

同步使用(在异步函数内):

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

ubbxdtey5#

使用该图像创建隐藏的<img>,然后使用jQuery的. width()和. height()

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

此处测试:JSFiddle
图像最初不是创建为隐藏的。它是创建的,然后获得宽度和高度,然后将其删除。这可能会导致大型图像的可见性非常短。在这种情况下,您必须将图像 Package 到另一个容器中,并使该容器隐藏,而不是图像本身隐藏。
另一个Fiddle没有按照gp.的答案添加到DOM中:here

相关问题