从url获取远程图像的宽度高度 [英] Get width height of remote image from url

查看:199
本文介绍了从url获取远程图像的宽度高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此警报为宽度和高度提供了未定义的值。我认为来自img.onload计算的图像的w和h值没有被传递给要返回的值,或者它可能会返回w和h 之前 onload计算它们:

So the alert gives undefined values for the width and height. I think the w and h values of the image from the img.onload calculation is not being passed to the values to return, or it may be returning w and h before the onload calculates them:

function getMeta(url){
 var w; var h;
 var img=new Image;
 img.src=url;
 img.onload=function(){w=this.width; h=this.height;};
 return {w:w,h:h}    
}

// "http://snook.ca/files/mootools_83_snookca.png" //1024x678
// "http://shijitht.files.wordpress.com/2010/08/github.png" //128x128

var end = getMeta("http://shijitht.files.wordpress.com/2010/08/github.png");
var w = end.w;
var h = end.h;
alert(w+'width'+h+'height');

如何让警报显示正确的宽度和高度?

How can I have the alert show the correct width and height?

http://jsfiddle.net/YtqXk/

推荐答案

使用jQuery获取图像大小



Get image size with jQuery

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



使用JavaScript获取图像大小



Get image size with JavaScript

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



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



Get image size with JavaScript (modern browsers, 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);

Use the above simply as: getMeta( "http://example.com/img.jpg" );

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

这篇关于从url获取远程图像的宽度高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆