我有一個輸入文本字段,其中用戶提供圖像的源URL,例如 http://mysite/images/STARTPAGE_LOGO.gif
是一個有效值。如何通過它知道圖像的大小url
我沒有任何img
標記或在我的HTML文檔中的其他東西。我如何確定用戶輸入的URL的圖像尺寸。
我有一個輸入文本字段,其中用戶提供圖像的源URL,例如 http://mysite/images/STARTPAGE_LOGO.gif
是一個有效值。如何通過它知道圖像的大小url
我沒有任何img
標記或在我的HTML文檔中的其他東西。我如何確定用戶輸入的URL的圖像尺寸。
有沒有方法來找出圖像的寬度和高度,而不會加載它,所以你必須動態加載它,這樣做你可以使用
function getDimensions(_src,_callback){
/* create a new image , not linked anywhere in document */
var img = document.createElement('img');
/* set the source of the image to what u want */
img.src=_src;
/* Wait the image to load and when its so call the callback function */
/* If you want the actual natural dimensions of the image use naturalWidth and natural height instead */
img.onload = function() { _callback(img.width,img.height) };
}
宣佈上述功能的純JavaScript精神,你可以這樣做
後getDimensions('http://mysite/images/STARTPAGE_LOGO.gif',function(w,h){
console.log("Height : ",h,"Width:",w);
});
HTML:
<input id="src" type="text" value="https://www.google.pl/images/srpr/logo3w.png"/>
JAVASCRIPT:上onload事件
var img = new Image; // create tmp image element
// is equal to document.createElement('img');
綁定函數,它會被自動加載圖像時調用。
img.onload = function(){
alert(this.width +" : " + this.height);
};
設置圖像的來源;
img.src = document.getElementById('src').value // get the value of input element;
出於好奇jQuery中:
$('<img/>').attr('src',$('#src').val()).bind('load',function(){
alert(this.width +' x ' + this.height);
});
任何理由downvote :) – abuduba 2012-08-13 13:10:13
的jQuery這樣簡單的東西是矯枉過正 – ShrekOverflow 2012-08-13 13:11:27
exaxctly他說什麼^ – gonchuki 2012-08-13 13:12:05
'size'是指以字節爲單位的大小還是像寬度和高度這樣的圖像屬性? – 2012-08-13 13:05:30
他意味着寬度和高度 – ShrekOverflow 2012-08-13 13:07:32
您將不得不動態加載它。這裏的答案說明如何?http://stackoverflow.com/questions/1310378/determining-image-file-size-dimensions-via-javascript – 2012-08-13 13:07:42