Retrieving Image Dimensions Accurately in Webkit Browsers
Measuring the true dimensions of an image can be challenging in Webkit browsers such as Safari and Chrome. Traditional methods like removing inline width and height attributes and measuring the image's actual dimensions fail to account for these browsers setting dimensions after the image loads.
Harnessing the Image's Onload Event
Instead of relying on timeouts, a more reliable approach is to utilize the image's onload event. This allows you to capture the dimensions once the image has fully loaded:
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. });
Leveraging NaturalHeight and NaturalWidth Attributes
Modern browsers support the HTML5 attributes naturalHeight and naturalWidth, which provide the true dimensions of an image regardless of CSS. This approach is more concise:
var pic_real_width = img.naturalWidth; var pic_real_height = img.naturalHeight;
By utilizing these techniques, you can accurately retrieve the real width and height of images in Webkit browsers, enabling more precise image manipulation and display.
The above is the detailed content of How Can I Accurately Get Image Dimensions in WebKit Browsers?. For more information, please follow other related articles on the PHP Chinese website!