是否有JavaScript或jQuery API或方法来获取页面上图像的尺寸?
当前回答
使用jQuery,你可以这样做:
var imgWidth = $("#imgIDWhatever").width();
其他回答
clientWidth和clienttheight是DOM属性,显示DOM元素内部维度的当前浏览器大小(不包括边距和边框)。在IMG元素的情况下,这将得到可见图像的实际尺寸。
var img = document.getElementById('imageid');
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
这是Node.js的替代答案。这可能不是OP的意思,但它可能会派上用场,似乎在问题的范围内。
这是一个使用Node.js的解决方案,该示例使用Next.js框架,但它可以与任何Node.js框架一起工作。它使用探针图像大小的NPM包从服务器端解析图像属性。
示例用例:我使用下面的代码从Airtable Automation脚本解析图像的大小,该脚本调用我自己的analyzeImage API并返回图像的道具。
import {
NextApiRequest,
NextApiResponse,
} from 'next';
import probe from 'probe-image-size';
export const analyzeImage = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
try {
const result = await probe('http://www.google.com/intl/en_ALL/images/logo.gif');
res.json(result);
} catch (e) {
res.json({
error: true,
message: process.env.NODE_ENV === 'production' ? undefined : e.message,
});
}
};
export default analyzeImage;
收益率:
{
"width": 276,
"height": 110,
"type": "gif",
"mime": "image/gif",
"wUnits": "px",
"hUnits": "px",
"length": 8558,
"url": "http://www.google.com/intl/en_ALL/images/logo.gif"
}
在我的例子中,我有一个File类型(保证是一个图像),我想要图像的尺寸,而不是将其加载到DOM上。
一般策略:将文件转换为ArrayBuffer→将ArrayBuffer转换为base64字符串→使用此作为image类的图像源→使用naturalHeight和naturalWidth来获取维度。
const fr = new FileReader();
fr.readAsArrayBuffer(image); // Image the 'File' object
fr.onload = () => {
const arrayBuffer: ArrayBuffer = fr.result as ArrayBuffer;
// Convert to base64. String.fromCharCode can hit a stack overflow error if you pass
// the entire arrayBuffer in, and iteration gets around this
let binary = '';
const bytes = new Uint8Array(arrayBuffer);
bytes.forEach(b => binary += String.fromCharCode(b));
const base64Data = window.btoa(binary);
// Create an image object. Note, a default width/height MUST be given to the constructor (per
// the documentation) or naturalWidth/Height will always return 0.
const imageObj = new Image(100, 100);
imageObj.src = `data:${image.type};base64,${base64Data}`;
imageObj.onload = () => {
console.log(imageObj.naturalWidth, imageObj.naturalHeight);
}
}
这允许您从文件中获得图像尺寸和纵横比,而无需渲染它。它可以使用fromEvent轻松地将onload函数转换为RxJS Observables,以获得更好的异步体验:
// fr is the file reader, and this is the same as fr.onload = () => { ... }
fromEvent(fr, 'load')
我认为这可能对2019年使用JavaScript和/或TypeScript的人有所帮助。
我发现以下内容是不正确的,就像一些人认为的那样:
let img = new Image();
img.onload = function() {
console.log(this.width, this.height) // Error: undefined is not an object
};
img.src = "http://example.com/myimage.jpg";
这是正确的:
let img = new Image();
img.onload = function() {
console.log(img.width, img.height)
};
img.src = "http://example.com/myimage.jpg";
结论:
在onload函数中使用img,而不是this。
使用jQuery,你可以这样做:
var imgWidth = $("#imgIDWhatever").width();
推荐文章
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- 用jQuery检查Internet连接是否存在?
- 如何使用滑动(或显示)函数在一个表行?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类
- 访问Handlebars.js每次循环范围之外的变量
- 如何用JavaScript截屏一个div ?
- 如何为其他域设置cookie