获取图像尺寸

JavaScript: Get image dimensions

本文关键字:图像 获取      更新时间:2023-09-26

我只有一个图片的URL。我只需要使用JavaScript来确定这个图像的高度和宽度。用户在页面上无法看到该图像。我怎么得到它的维数?

var img = new Image();
img.onload = function(){
  var height = img.height;
  var width = img.width;
  // code here to use the dimensions
}
img.src = url;

新建Image

var img = new Image();

设置src

img.src = your_src

获取widthheight

//img.width
//img.height

naturalWidthnaturalHeight

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%; }

使用函数并等待它完成。

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

组合承诺&打印稿打字:

/**
 * 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;
  });
};

用法:

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

如果您有来自输入表单的图像文件。你可以像这样使用

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

使用jQuery获取图像大小

function getMeta(url){
    $("<img/>",{
        load : function(){
            alert(this.width+' '+this.height);
        },
        src  : url
    });
}

使用JavaScript获取图像大小

function getMeta(url){   
    var img = new Image();
    img.onload = function(){
        alert( this.width+' '+ this.height );
    };
    img.src = url;
}

使用JavaScript获取图像大小(现代浏览器,IE9+)

function getMeta(url){   
    var img = new Image();
    img.addEventListener("load", function(){
        alert( this.naturalWidth +' '+ this.naturalHeight );
    });
    img.src = url;
}

可以简单地使用:getMeta("http://example.com/img.jpg");

https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement

类似的问题在这里使用JQuery进行提问和回答:

从url

获取远程图像的宽度和高度
function getMeta(url){
  $("<img/>").attr("src", url).load(function(){
     s = {w:this.width, h:this.height};
     alert(s.w+' '+s.h);      
  }); 
}
getMeta("http://page.com/img.jpg");

下面的代码为页面上的每个图像添加图像属性heightwidth

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
function addImgAttributes()
{
    for( i=0; i < document.images.length; i++)
    { 
        width = document.images[i].width;
        height = document.images[i].height;
        window.document.images[i].setAttribute("width",width);
        window.document.images[i].setAttribute("height",height);
    }
}
</script>
</head>
<body onload="addImgAttributes();">
<img src="2_01.jpg"/>
<img src="2_01.jpg"/>
</body>
</html>