是否有JavaScript或jQuery API或方法来获取页面上图像的尺寸?
当前回答
在使用真实图像大小之前,您应该加载源图像。如果使用jQuery框架,可以以简单的方式获得真实图像大小。
$("ImageID").load(function(){
console.log($(this).width() + "x" + $(this).height())
})
其他回答
jQuery的答案:
$height = $('#image_id').height();
$width = $('#image_id').width();
在我的例子中,我有一个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')
其他所有人都忘记了的事情是,你不能在加载前检查图像大小。当作者检查所有发布的方法时,它可能只在本地主机上工作。
由于这里可以使用jQuery,请记住'ready'事件是在图像加载之前触发的。$('#xxx').width()和.height()应该在onload事件或以后触发。
这是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"
}
当页面在JavaScript或jQuery中加载时,你可以像这样应用onload处理程序属性:
$(document).ready(function(){
var width = img.clientWidth;
var height = img.clientHeight;
});
推荐文章
- 用jQuery切换DIV背景图像
- 'React'指的是一个UMD全局,但当前文件是一个模块
- 为什么useState不触发重新渲染?
- 如何使用回调与useState挂钩在反应
- 网络请求失败
- 如何使用JavaScript大写字符串中每个单词的第一个字母?
- 如何使用箭头函数(公共类字段)作为类方法?
- 使用Javascript的atob解码base64不能正确解码utf-8字符串
- 如何阻止恶意代码欺骗“Origin”报头来利用CORS?
- Angular JS:当我们已经有了具有作用域的指令控制器时,指令的link函数还需要什么?
- 我如何在JavaScript中转换对象数组为一个对象?
- 如何让一个按钮将我的页面重定向到另一个页面?
- 如何让元素被点击(对于整个文档)?
- 我如何检查如果一个变量是JavaScript字符串?
- 如何检测如果多个键被按下一次使用JavaScript?