ユーザーが画像のソースURLを提供する入力テキストフィールドがあります。たとえば http://mysite/images/STARTPAGE_LOGO.gif
、有効な値です。
img
HTMLドキュメントにタグなどはありません。ユーザーが入力した URL に存在する画像のサイズを特定するにはどうすればよいですか。
ユーザーが画像のソースURLを提供する入力テキストフィールドがあります。たとえば http://mysite/images/STARTPAGE_LOGO.gif
、有効な値です。
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"/>
ジャバスクリプト:
var img = new Image; // create tmp image element
// is equal to document.createElement('img');
onload イベントで関数をバインドします。画像が読み込まれると自動的に呼び出されます。
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 );
});