pil获取图像的宽度
One massive help provided by CSS in aiding developers to create responsive designs is max-width
. I always set img
, iframe
, and embed
tags to max-width: 100%
so that they aren't allowed bleed through their parent and stretch the page on mobiles, but I recently asked myself if it was possible to get an image's "true" size with JavaScript. I wanted the real image dimensions without any CSS modifications. MDN informed me of a property I'd never heard of which provided me the information I wanted!
CSS在帮助开发人员创建响应式设计方面提供的一项巨大帮助是max-width
。 我总是将img
, iframe
和embed
标签设置为max-width: 100%
以便不允许它们通过其父对象流血并在移动设备上拉伸页面,但是我最近问自己,是否有可能获得图像的“真”使用JavaScript的大小”。 我想要没有任何CSS修改的真实图像尺寸。 MDN通知我一个我从未听说过的财产,它为我提供了我想要的信息!
JavaScript (The JavaScript)
Using some JavaScript magic, we can get the real dimensions of an image:
使用一些JavaScript魔术,我们可以获得图像的真实尺寸:
myImage.addEventListener('load', function() {
console.log('My width is: ', this.naturalWidth);
console.log('My height is: ', this.naturalHeight);
});
I had never heard of these read only naturalWidth
and naturalHeight
properties but I'm happy they're available. No matter how terrible CSS mangles an img
element, the original image dimensions are available. Of course the image's onload
event should be triggered before checking the image dimensions as you cannot know them without the image being loaded.
我从未听说过这些只读的naturalWidth
和naturalHeight
属性,但很高兴它们可用。 无论CSS多么糟糕地处理img
元素,原始图像尺寸都可用。 当然,应该在检查图像尺寸之前触发图像的onload
事件,因为如果不加载图像就无法知道它们。
pil获取图像的宽度