Home >Web Front-end >JS Tutorial >How to Accurately Retrieve Image Dimensions in WebKit Browsers (Safari and Chrome)?

How to Accurately Retrieve Image Dimensions in WebKit Browsers (Safari and Chrome)?

Susan Sarandon
Susan SarandonOriginal
2024-12-03 16:09:14286browse

How to Accurately Retrieve Image Dimensions in WebKit Browsers (Safari and Chrome)?

Retrieving Accurate Image Dimensions in Webkit Browsers (Safari, Chrome)

In the realm of Javascript image manipulation, obtaining the true width and height of an image can pose challenges, particularly in Webkit browsers like Safari and Chrome.

Issue Overview

When utilizing jQuery in Firefox 3, IE7, and Opera 9, the following code snippet effectively extracts the actual image dimensions:

var pic = $("img");
pic.removeAttr("width");
pic.removeAttr("height");
var pic_real_width = pic.width();
var pic_real_height = pic.height();

However, in Webkit browsers, this approach yields incorrect values of 0.

Solution: Javascript's Image Loading Event

The solution lies in tapping into the onload event of the image element. The modified code below accomplishes this:

var img = $("img")[0]; // Get the image element

$("<img/>") // Make a virtual copy of the image to prevent CSS interference
    .attr("src", $(img).attr("src"))
    .load(function() {
        pic_real_width = this.width;
        pic_real_height = this.height;
    });

By creating a memory copy of the image and utilizing the this keyword within the load event, we bypass any potential CSS effects that could alter the image's dimensions.

Alternative: HTML5 Image Attributes

For compatibility with HTML5 browsers, you can also leverage the naturalHeight and naturalWidth attributes:

var pic_real_width = img.naturalWidth;
var pic_real_height = img.naturalHeight;

The above is the detailed content of How to Accurately Retrieve Image Dimensions in WebKit Browsers (Safari and Chrome)?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn