问题描述
到目前为止我有这个代码:
I have this code so far:
var img = document.getElementById('draggable');
var width = img.clientWidth;
var height = img.clientHeight;
然而,这会让我获得html属性--css样式。我想得到文件的实际图像资源的尺寸。
However this gets me the html attributes - css styles. I want to get dimensions of the actual image resource, of the file.
我需要这个,因为在上传图像时,它的宽度设置为0px而且我不知道为什么或在哪里发生这种情况。为了防止它,我想获得实际尺寸并重置它们。这可能吗?
I need this because upon uploading an image, it's width gets set to 0px and I have no idea why or where this is happening. To prevent it I want to get the actual dimension and reset them. Is this possible?
编辑:即使我尝试获得naturalWidth,我也会得到0。我添加了一张图片。奇怪的是,它只会在我上传新文件时发生,并在刷新后才能正常工作。
Even when I try to get naturalWidth I get 0 as a result. I've added a picture. The weird thing is that it only happens when I upload new files and upon refresh it's working as it should.
推荐答案
您可以使用 naturalWidth
和 naturalHeight
,这些属性包含实际的,未修改的宽度和高度图像,但你必须等到图像加载才能得到它们
You could use naturalWidth
and naturalHeight
, these properties contain the actual, non-modified width and height of the image, but you have to wait until the image has loaded to get them
var img = document.getElementById('draggable');
img.onload = function() {
var width = img.naturalWidth;
var height = img.naturalHeight;
}
仅支持IE9及以上版本,如果您必须支持旧浏览器你可以创建一个新的图像,将它的源设置为同一个图像,如果你不修改图像的大小,它将返回图像的自然大小,因为没有给出其他大小时这将是默认值
This is only supported from IE9 and up, if you have to support older browser you could create a new image, set it's source to the same image, and if you don't modify the size of the image, it will return the images natural size, as that would be the default when no other size is given
var img = document.getElementById('draggable'),
new_img = new Image();
new_img.onload = function() {
var width = this.width,
heigth = this.height;
}
new_img.src = img.src;
这篇关于如何使用javascript或jquery获取图像的自然尺寸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!