使用JavaScript,如何在不将文档插入文档的情况下确定文档中没有的图像大小?
我可以使用AJAX下载图像并以编程方式检查其高度和宽度吗?
像...一样的东西。
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var imageSize = MEGIC_GET_FILE_SIZE_FUNCTION(xmlhttp);
alert("The image is "+imageSize.width+","+imageSize.height+".");
}
}
xmlhttp.open("GET","lena.jpg",true);
xmlhttp.send();
我将使用Raphael,所以如果它提供了这种效果的功能,那么它就适合我的需要。
答案 0 :(得分:8)
你不需要ajax。
var img = new Image();
img.onload = function() {
alert("The image is " + this.width + "x" + this.height);
}
img.src = "lena.jpg";
答案 1 :(得分:2)
var img = new Image();
img.src = url;
var height = img.height;
var width = img.width;
答案 2 :(得分:2)
这是你的fiddle。只需使用Image
对象。
答案 3 :(得分:1)
您无需将其添加到文档中以测量其大小,但您必须等待它至少部分加载。如果您需要一次为多个图像执行此操作,并在大小可用时立即调用回调,则可以使用我的imageloader模块:
var ImageLoader = {
maxChecks: 1000,
list: [],
intervalHandle : null,
loadImage : function (callback, url) {
var img = new Image ();
img.src = url;
if (img.width && img.height) {
callback (mg.width, img.height, url, 0);
}
else {
var obj = {image: img, url: url, callback: callback, checks: 1};
var i;
for (i=0; i < this.list.length; i++) {
if (this.list[i] == null)
break;
}
this.list[i] = obj;
if (!this.intervalHandle)
this.intervalHandle = setInterval(this.interval, 30);
}
},
// called by setInterval
interval : function () {
var count = 0;
var list = ImageLoader.list, item;
for (var i=0; i<list.length; i++) {
item = list[i];
if (item != null) {
if (item.image.width && item.image.height) {
item.callback (item.image.width, item.image.height, item.url, item.checks);
ImageLoader.list[i] = null;
}
else if (item.checks > ImageLoader.maxChecks) {
item.callback (0, 0, item.url, item.checks);
ImageLoader.list[i] = null;
}
else {
count++;
item.checks++;
}
}
}
if (count == 0) {
ImageLoader.list = [];
clearInterval (ImageLoader.intervalHandle);
delete ImageLoader.intervalHandle;
}
}
};
答案 4 :(得分:-1)
如果您知道图像的来源,可以使用javascript图像对象:
function MEGIC_GET_FILE_SIZE_FUNCTION(src){
var img = new Image();
img.src = src;
return {height: img.height, width: img.width};
}