得到真正的宽度和高度的图像与JavaScript?(在Safari/铬)
-
11-07-2019 - |
题
我创造一个jQuery插件。
我如何获得真正的图像的宽度和高度与Javascript在野生动物园?
以下作品有Firefox3,IE7和歌剧9:
var pic = $("img")
// need to remove these in of case img-element has set width and height
pic.removeAttr("width");
pic.removeAttr("height");
var pic_real_width = pic.width();
var pic_real_height = pic.height();
但在其浏览器就像野生动物园和谷歌铬值的0.
解决方案
WebKit浏览器设定的高度,并且图像被加载之后width属性。而不是使用超时,我建议你使用图像的onload事件。下面是一个简单示例:
var img = $("img")[0]; // Get my img elem
var pic_real_width, pic_real_height;
$("<img/>") // Make in memory copy of image to avoid css issues
.attr("src", $(img).attr("src"))
.load(function() {
pic_real_width = this.width; // Note: $(this).width() will not
pic_real_height = this.height; // work for in memory images.
});
要避免任何的影响CSS的可能对图像的尺寸,上面的代码使得图像的在存储器中的副本。这是通过之后FDisk 提出了一个非常巧妙的解决方案。
您还可以使用naturalHeight
和naturalWidth
HTML5属性。
其他提示
function getOriginalWidthOfImg(img_element) {
var t = new Image();
t.src = (img_element.getAttribute ? img_element.getAttribute("src") : false) || img_element.src;
return t.width;
}
您不需要从图像或图像尺寸属性删除样式。只是用JavaScript创建一个元素,并获得所创建的对象的宽度。
问题的根源在于,WebKit浏览器(Safari和铬)负载JavaScript和并联CSS信息。因此,已计算CSS的造型效果之前的JavaScript可以执行,返回错误的答案。 jQuery中,我发现,解决的办法是等到document.readyState ==“完成”,.e.g。,
jQuery(document).ready(function(){
if (jQuery.browser.safari && document.readyState != "complete"){
//console.info('ready...');
setTimeout( arguments.callee, 100 );
return;
}
... (rest of function)
至于宽度和高度去...这取决于你在做什么你可能想offsetWidth和的offsetHeight,其中包括诸如边界和填充。
有很多的讨论,在大约一个问题,如果图像是从WebKit的缓存加载onload
不会触发事件接受的答案。
在我的情况下,onload
火的缓存图片,但高度和宽度仍为0。一个简单的setTimeout
解决了这个问题对我来说:
$("img").one("load", function(){
var img = this;
setTimeout(function(){
// do something based on img.width and/or img.height
}, 0);
});
我可以不说话,为什么即使在图像从缓存加载onload
事件被解雇(改善jQuery的1.4 / 1.5) - 但如果你仍然遇到这个问题,也许我的回答的组合和var src = img.src; img.src = ""; img.src = src;
技术将工作。
(请注意,我的目的,我不关心预先定义的尺寸,无论是在图像的属性或CSS样式 - 但你可能要删除这些,按照哈维的回答或克隆图像。)
这对我的作品(狩猎3.2),通过从window.onload
事件中激活:
$(window).load(function() {
var pic = $('img');
pic.removeAttr("width");
pic.removeAttr("height");
alert( pic.width() );
alert( pic.height() );
});
您可以通过编程方式获取图像,并检查使用Javascript的尺寸,而不必使用DOM混乱的。
var img = new Image();
img.onload = function() {
console.log(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
约image.naturalHeight
和image.naturalWidth
性质什么?
似乎在Chrome,Safari和Firefox做工精细回不少版本,但不是在所有的IE8甚至IE9。
我们如何得到正确的实际尺寸无闪烁的实像:
(function( $ ){
$.fn.getDimensions=function(){
alert("First example:This works only for HTML code without CSS width/height definition.");
w=$(this, 'img')[0].width;
h=$(this, 'img')[0].height;
alert("This is a width/height on your monitor: " + $(this, 'img')[0].width+"/"+$(this, 'img')[0].height);
//This is bad practice - it shows on your monitor
$(this, 'img')[0].removeAttribute( "width" );
$(this, 'img')[0].removeAttribute( "height" );
alert("This is a bad effect of view after attributes removing, but we get right dimensions: "+ $(this, 'img')[0].width+"/"+$(this, 'img')[0].height);
//I'am going to repare it
$(this, 'img')[0].width=w;
$(this, 'img')[0].height=h;
//This is a good practice - it doesn't show on your monitor
ku=$(this, 'img').clone(); //We will work with a clone
ku.attr( "id","mnbv1lk87jhy0utrd" );//Markup clone for a final removing
ku[0].removeAttribute( "width" );
ku[0].removeAttribute( "height" );
//Now we still get 0
alert("There are still 0 before a clone appending to document: "+ $(ku)[0].width+"/"+$(ku)[0].height);
//Hide a clone
ku.css({"visibility" : "hidden",'position':'absolute','left':'-9999px'});
//A clone appending
$(document.body).append (ku[0]);
alert("We get right dimensions: "+ $(ku)[0].width+"/"+$(ku)[0].height);
//Remove a clone
$("#mnbv1lk87jhy0utrd").remove();
//But a next resolution is the best of all. It works in case of CSS definition of dimensions as well.
alert("But if you want to read real dimensions for image with CSS class definition outside of img element, you can't do it with a clone of image. Clone method is working with CSS dimensions, a clone has dimensions as well as in CSS class. That's why you have to work with a new img element.");
imgcopy=$('<img src="'+ $(this, 'img').attr('src') +'" />');//new object
imgcopy.attr( "id","mnbv1lk87jhy0aaa" );//Markup for a final removing
imgcopy.css({"visibility" : "hidden",'position':'absolute','left':'-9999px'});//hide copy
$(document.body).append (imgcopy);//append to document
alert("We get right dimensions: "+ imgcopy.width()+"/"+imgcopy.height());
$("#mnbv1lk87jhy0aaa").remove();
}
})( jQuery );
$(document).ready(function(){
$("img.toreaddimensions").click(function(){$(this).getDimensions();});
});
它与
Jquery的具有两个属性称为naturalWidth和naturalHeight,可以以这种方式使用。
$('.my-img')[0].naturalWidth
$('.my-img')[0].naturalHeight
,其中My-IMG是用于选择我的图像的类名。
如前所述, 哈维回答 不会的工作,如果图像是在高速缓存。该问题响应其不能发射的装载事件就缓存的图像,因此,如果宽度attrs没有明确地设定在img tag,唯一可靠的方式获取的图像是等待 window.load
事件被解雇。
的 window.load
活动将火 总是, ,所以它的安全访问的宽度和img之后,没有任何伎俩。
$(window).load(function(){
//these all work
$('img#someId').css('width');
$('img#someId').width();
$('img#someId').get(0).style.width;
$('img#someId').get(0).width;
});
如果你需要得到大小的动态加载的图像,可能会得到缓存(先前载的),可以使用哈维的方法以及查询串的触发一个高速缓冲刷新。缺点是,它会引起的另一个请求到服务器,用于img,已经缓存,并应该已经可以使用。愚蠢的。.
var pic_real_width = 0,
img_src_no_cache = $('img#someId').attr('src') + '?cache=' + Date.now();
$('<img/>').attr('src', img_src_no_cache).load(function(){
pic_real_width = this.width;
});
ps:如果你有一个查询的 img.src
已经,你会需要 分析它 并添加额外的参数清除高速缓存。
$("#myImg").one("load",function(){
//do something, like getting image width/height
}).each(function(){
if(this.complete) $(this).trigger("load");
});
从Chris的评论: http://api.jquery.com/load-event/
我的情况可能是有一点不同。我通过javascript动态改变的图像的src和需要确保新的图像的尺寸成比例,以适应一个固定的容器(在照片库)。我最初只是删除了宽度和它被加载(通过图像的加载事件)和计算的最佳尺寸之后重置这些后的图像的高度属性。然而,这并不在Safari和IE可能(我没有在IE测试它彻底,但图像甚至不显示,所以...)工作。
总之,Safari浏览器保持先前图像的尺寸,以便尺寸总是一个图像的后面。我认为这有什么做缓存。因此最简单的解决方法就是克隆图像,并把它添加到DOM(重要的是,它被添加到DOM中获得与和高度)。给出的图像隐藏能见度值(不使用显示器没有,因为它不会工作)。你之后得到的尺寸删除克隆。
下面是使用jQuery我的代码:
// Hack for Safari and others
// clone the image and add it to the DOM
// to get the actual width and height
// of the newly loaded image
var cloned,
o_width,
o_height,
src = 'my_image.jpg',
img = [some existing image object];
$(img)
.load(function()
{
$(this).removeAttr('height').removeAttr('width');
cloned = $(this).clone().css({visibility:'hidden'});
$('body').append(cloned);
o_width = cloned.get(0).width; // I prefer to use native javascript for this
o_height = cloned.get(0).height; // I prefer to use native javascript for this
cloned.remove();
$(this).attr({width:o_width, height:o_height});
})
.attr(src:src);
这个解决方案适用在任何情况下。
现在有一个jQuery插件, event.special.load
, 处理的案件负载上的事件的高速缓存图像没火: http://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js
最近,我需要找到的宽度和高度设定.dialog表示图形的默认大小。溶液I的用途是:
graph= $('<img/>', {"src":'mySRC', id:'graph-img'});
graph.bind('load', function (){
wid = graph.attr('width');
hei = graph.attr('height');
graph.dialog({ autoOpen: false, title: 'MyGraphTitle', height:hei, width:wid })
})
有关我这个作品在FF3,歌剧10,IE 8,7,6
P.S。你可能会发现一些更多的解决方案看起来像灯箱或彩盒
一些插件内要添加到哈维的回答,<击> 保罗爱尔兰的github上 行使>的大卫Desandro的gitgub提供了一个称为imagesLoaded()是同样的原理工作的功能,和周围的一些浏览器的缓存图片的问题变得未焙烧.load()事件(带有聪明original_src - > data_uri - > original_src切换)。
这是被广泛使用,并定期更新,这有助于它是最可靠的解决方案的问题,IMO。
这同时适用于高速缓存和动态加载的图像。
function LoadImage(imgSrc, callback){
var image = new Image();
image.src = imgSrc;
if (image.complete) {
callback(image);
image.onload=function(){};
} else {
image.onload = function() {
callback(image);
// clear onLoad, IE behaves erratically with animated gifs otherwise
image.onload=function(){};
}
image.onerror = function() {
alert("Could not load image.");
}
}
}
要使用此脚本:
function AlertImageSize(image) {
alert("Image size: " + image.width + "x" + image.height);
}
LoadImage("http://example.org/image.png", AlertImageSize);
我已经做了一些变通的效用函数,使用imagesLoaded jQuery插件: https://github.com/desandro/imagesloaded
function waitForImageSize(src, func, ctx){
if(!ctx)ctx = window;
var img = new Image();
img.src = src;
$(img).imagesLoaded($.proxy(function(){
var w = this.img.innerWidth||this.img.naturalWidth;
var h = this.img.innerHeight||this.img.naturalHeight;
this.func.call(this.ctx, w, h, this.img);
},{img: img, func: func, ctx: ctx}));
},
您可以通过传递的网址,功能和它的上下文中使用此。图像加载,并返回生成的图像,其宽度和高度之后执行功能。
waitForImageSize("image.png", function(w,h){alert(w+","+h)},this)
如果该图像已被使用,您应该:
将图像尺寸设置为初始值
image.css('宽度', '初始');image.css('高度', '初始');
获取尺寸
var 原始宽度 = $(this).width();var 原始高度 = $(this).height();
可以使用HTML图像元素的naturalWidth和naturalHeight性质。 (这里有更多信息)。
您会使用这样的:
//you need a reference to the DOM element, not a jQuery object. It would be better if you can use document.getElementByTagsName or ID or any other native method
var pic = $("img")[0];
var pic_real_width = pic.naturalWidth;
var pic_real_height = pic.naturalHeight;
看起来这从版本8的工作原理在所有浏览器除了在IE和下方。
有关的功能,你不想改变原来的位置或图像。
$(this).clone().removeAttr("width").attr("width");
$(this).clone().removeAttr("height").attr("height);
我检查了迪奥的答案,它为我的伟大工程。
$('#image').fadeIn(10,function () {var tmpW = $(this).width(); var tmpH = $(this).height(); });
请确保您ASO调用所有功能。该处理与在淡入()的调用器功能的图像尺寸。
感谢。
我用不同的方法,只是让Ajax调用服务器,以获得图像大小时图像对象正在使用中。
//make json call to server to get image size
$.getJSON("http://server/getimagesize.php",
{"src":url},
SetImageWidth
);
//callback function
function SetImageWidth(data) {
var wrap = $("div#image_gallery #image_wrap");
//remove height
wrap.find("img").removeAttr('height');
//remove height
wrap.find("img").removeAttr('width');
//set image width
if (data.width > 635) {
wrap.find("img").width(635);
}
else {
wrap.find("img").width(data.width);
}
}
和当然服务器端代码:
<?php
$image_width = 0;
$image_height = 0;
if (isset ($_REQUEST['src']) && is_file($_SERVER['DOCUMENT_ROOT'] . $_REQUEST['src'])) {
$imageinfo = getimagesize($_SERVER['DOCUMENT_ROOT'].$_REQUEST['src']);
if ($imageinfo) {
$image_width= $imageinfo[0];
$image_height= $imageinfo[1];
}
}
$arr = array ('width'=>$image_width,'height'=>$image_height);
echo json_encode($arr);
?>
此工作跨浏览器
var img = new Image();
$(img).bind('load error', function(e)
{
$.data(img, 'dimensions', { 'width': img.width, 'height': img.height });
});
img.src = imgs[i];
通过使用得到的尺寸
$(this).data('dimensions').width;
$(this).data('dimensions').height;
干杯!
另一个建议是使用 imagesLoaded插件。
$("img").imagesLoaded(function(){
alert( $(this).width() );
alert( $(this).height() );
});
$(document).ready(function(){
var image = $("#fix_img");
var w = image.width();
var h = image.height();
var mr = 274/200;
var ir = w/h
if(ir > mr){
image.height(200);
image.width(200*ir);
} else{
image.width(274);
image.height(274/ir);
}
});
//此代码有助于示出了具有200 * 274图像渔政
这里的触发时所选图像加载事件的跨浏览器的解决方案: HTTP://desandro.github .IO / imagesloaded / 你可以查找imagesLoaded()函数中的高度和宽度。
在这个线程试图找到我自己的问题的答案跌跌撞撞。我试图在加载后一个函数来获取图像的宽度/高度,并保持未来与0。我觉得这可能是你在找什么,不过,因为它为我的作品:
tempObject.image = $('<img />').attr({ 'src':"images/prod-" + tempObject.id + ".png", load:preloader });
xmlProjectInfo.push(tempObject);
function preloader() {
imagesLoaded++;
if (imagesLoaded >= itemsToLoad) { //itemsToLoad gets set elsewhere in code
DetachEvent(this, 'load', preloader); //function that removes event listener
drawItems();
}
}
function drawItems() {
for(var i = 1; i <= xmlProjectInfo.length; i++)
alert(xmlProjectInfo[i - 1].image[0].width);
}
看看这个仓库在github上!
大实施例来检查使用Javascript宽度和高度
https://github.com/AzizAK/ImageRealSize
---被修改从一些意见请求..
Javascript代码:
function CheckImageSize(){
var image = document.getElementById("Image").files[0];
createReader(image, function (w, h) {
alert("Width is: " + w + " And Height is: "+h);
});
}
function createReader(file, whenReady) {
var reader = new FileReader;
reader.onload = function (evt) {
var image = new Image();
image.onload = function (evt) {
var width = this.width;
var height = this.height;
if (whenReady) whenReady(width, height);
};
image.src = evt.target.result;
};
reader.readAsDataURL(file);
}
和HTML代码:
<html>
<head>
<title>Image Real Size</title>
<script src="ImageSize.js"></script>
</head>
<body>
<input type="file" id="Image"/>
<input type="button" value="Find the dimensions" onclick="CheckImageSize()"/>
</body>
<html>