Given a URL to an image (and not the image itself), what's the most efficient of getting it's dimensions? I would like to change the height and width attributes in the image tag (<img>
) if it is greater than 200x200. However, if it's smaller than that, then I'd like to keep the size as it is. (I'm using ASP.NET/C#)
views:
228answers:
4If you know that it's a JPEG you can just pull the first few bytes and parse the width/height from the image header.
Other image formats may be tougher to do. I think since PNG does everything in chunks you can't just do this sort of header inspection.
http://www.brettb.com/ASPNETUploadImageSize.asp
The code sample comes from the above site. This is for an uploaded image, but it shows you how to get the informatin from a file stream:
private void ButtonUpload_Click(object sender, System.EventArgs e) {
//Determine type and filename of uploaded image
string UploadedImageType = UploadedPicture.PostedFile.ContentType.ToString().ToLower();
string UploadedImageFileName = UploadedPicture.PostedFile.FileName;
//Create an image object from the uploaded file
System.Drawing.Image UploadedImage = System.Drawing.Image.FromStream(UploadedPicture.PostedFile.InputStream);
//Determine width and height of uploaded image
float UploadedImageWidth = UploadedImage.PhysicalDimension.Width;
float UploadedImageHeight = UploadedImage.PhysicalDimension.Height;
//Check that image does not exceed maximum dimension settings
if (UploadedImageWidth > 600 || UploadedImageHeight > 400) {
Response.Write("This image is too big - please resize it!");
}
}
If you don't want to check the properties of the image by loading it first you can do it with javascript:
<img src="image.jpg" onload="if( this.width > 200 ) this.width = 200;">
Instead of trying to check for the dimensions (which would be a waste, since you would almost always have to download the entire image and process it), why not just place the image in a <div>
element and set the max-height
and max-width
styles of the container to the dimensions you want?
The other option is to fetch the image once when you become aware of it, resize it to fit in your container appropriately, store it on your server, and serve up that.