javascript - 如何通过url知道图片的大小

标签 javascript dom image-loading

我有一个输入文本字段,用户在其中提供图像的源网址, 例如 http://mysite/images/STARTPAGE_LOGO.gif 是一个有效值。

我的 html 文档中没有任何 img 标记或其他内容。我如何确定用户输入的 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);
});

关于javascript - 如何通过url知道图片的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11934802/

相关文章:

javascript - JavaScript 中 % 符号的不同用法

javascript - 使用 jQuery 选择器时的默认上下文是什么?

javascript - image.onload 事件和浏览器缓存

android - 通过 Android Universal Image Loader 缓存所有图像

javascript - 包含DIV的显示宽度

javascript - 在计算数字的阶乘时,如何写出每个单独的数字以及星号符号?

php - 使用 DOM 抓取网站的标题

javascript - 如何在纯 JavaScript 中实现 jQuery 的 .wrapInner() 函数?

java - 使用glide将图片插入ArrayList

javascript - 带按钮的 AngularJS 输入指令