JQu*_*eer 80 html javascript image
我只有一个图像的URL.我需要仅使用JavaScript来确定此图像的高度和宽度.页面上的用户无法看到图像.我怎样才能得到它的尺寸?
Shu*_*mii 182
var img = new Image();
img.onload = function(){
var height = img.height;
var width = img.width;
// code here to use the dimensions
}
img.src = url;
Run Code Online (Sandbox Code Playgroud)
nc3*_*c3b 40
做一个新的 Image
var img = new Image();
Run Code Online (Sandbox Code Playgroud)
设置 src
img.src = your_src
Run Code Online (Sandbox Code Playgroud)
得到width
和height
//img.width
//img.height
Run Code Online (Sandbox Code Playgroud)
这使用该功能并等待它完成.
http://jsfiddle.net/SN2t6/118/
function getMeta(url){
var r = $.Deferred();
$('<img/>').attr('src', url).load(function(){
var s = {w:this.width, h:this.height};
r.resolve(s)
});
return r;
}
getMeta("http://www.google.hr/images/srpr/logo3w.png").done(function(test){
alert(test.w + ' ' + test.h);
});
Run Code Online (Sandbox Code Playgroud)
var img = document.createElement("img");
img.onload = function (event)
{
console.log("natural:", img.naturalWidth, img.naturalHeight);
console.log("width,height:", img.width, img.height);
console.log("offsetW,offsetH:", img.offsetWidth, img.offsetHeight);
}
img.src = "image.jpg";
document.body.appendChild(img);
// css for tests
img { width:50%;height:50%; }
Run Code Online (Sandbox Code Playgroud)
结合承诺和打字稿输入:
/**
* Returns image dimensions for specified URL.
*/
export const getImageDimensions = (url: string): Promise<{width: number, height: number}> => {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve({
width: img.width,
height: img.height,
});
img.onerror = (error) => reject(error);
img.src = url;
});
};
Run Code Online (Sandbox Code Playgroud)
用法:
try {
const {width, height} = await getImageDimensions(entry.NWS_IMAGE);
console.log(`Image dimensions: ${width}px x ${height}px`);
} catch (e) {
// Could not load image from specified URL
console.error(e);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您有输入表单中的图像文件。你可以这样使用
let images = new Image();
images.onload = () => {
console.log("Image Size", images.width, images.height)
}
images.onerror = () => result(true);
let fileReader = new FileReader();
fileReader.onload = () => images.src = fileReader.result;
fileReader.onerror = () => result(false);
if (fileTarget) {
fileReader.readAsDataURL(fileTarget);
}
Run Code Online (Sandbox Code Playgroud)