How to get Width and Height of dynamic image in Chrome
I want to share the tip to get width and height of dynamic image in Chrome
Introduction
While doing my project, I have a problem to get Width and Height of dynamic image and after several re-searching, I have found the solution to fix that issue.
Background
Imagine that you want to have a feature to allow your users to view the image in the popup by jQuery but you cannot get exactly image's width and image's height in Chrome although it works well on FF or IE 10
Using the code
The idea to fix the issue above is using the memory image and get the width and height from the memory image
Memory Image
//
$("#imgImagePreview").attr("src", imageUrl);
var picRealWidth, picRealHeight;
$("<img/>")
.attr("src", $("#imgImagePreview").attr("src"))
.load(function () {
picRealWidth = this.width; // Note: $(this).width() will not
picRealHeight = this.height; // work for in memory images.
});
//
One more point, we have to delay the reading code a little bit to make sure we have a real width and height
setTimeout(function () {
$("#toPopup").fadeIn(0500).width(picRealWidth + 20).height(picRealHeight + 40);
$("#backgroundPopup").css("opacity", "0.7");
$("#backgroundPopup").fadeIn(0001);
popupStatus = 1;
}, 50);
//
Points of Interest
This's a simple article to reduce the researching time if you have faced this issue. It's also not a common issue since it just happen in Chrome.
Happy programming :)