bom*_*tic 82 javascript jquery base64 image dimensions
我有一个base64 img encoded
你可以在这里找到的.我怎样才能得到它的高度和宽度?
gp.*_*gp. 132
var i = new Image();
i.onload = function(){
alert( i.width+", "+i.height );
};
i.src = imageData;
Run Code Online (Sandbox Code Playgroud)
Esc*_*ape 27
对于同步使用,只需将其包装成这样的承诺:
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
})
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用await来获取同步编码风格的数据:
var dimensions = await getImageDimensions(file)
Run Code Online (Sandbox Code Playgroud)
War*_*ama 11
更现代的解决方案是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
});
Run Code Online (Sandbox Code Playgroud)
同步使用(在异步函数内):
let img = new Image();
img.src = "myImage.png";
await img.decode();
let width = img.width;
let height = img.height;
// Do something with dimensions
Run Code Online (Sandbox Code Playgroud)
我发现使用.naturalWidth和.naturalHeight效果最佳。
var img = new Image();
img.onload = function() {
var imgWidth = img.naturalWidth,
imgHeight = img.naturalHeight;
};
Run Code Online (Sandbox Code Playgroud)
仅现代浏览器支持此功能。http://www.jacklmoore.com/notes/naturalwidth-and-naturalheight-in-ie/