Friday, July 31, 2009

How to get uploaded image dimensions in asp.net

If you want to know the image dimension you can get the dimensions by using the following code snippet by providing the image path to the method:

public string getImageDimensions(string strPath)
{
System.Drawing.Image imgFromFile= System.Drawing.Image.FromFile(strPath);
float imgWidth = imgFromFile.PhysicalDimension.Width;
float imgHeight = imgFromFile.PhysicalDimension.Height;
string size= imgWidth.toString()+","+imgHeight.toString();
return size;
}

Where,
strPath is the path of the file.

Similary we can get the get uploaded image dimensions as follows:

public string getImageDimensions(Stream streamImgFile)
{
System.Drawing.Image imgFromStream= System.Drawing.Image.FromStream(streamImgFile);
float imgWidth = imgFromStream.PhysicalDimension.Width;
float imgHeight = imgFromStream.PhysicalDimension.Height;
string size= imgWidth.toString()+","+imgHeight.toString();
return size;
}


For e.g.here in the following code imgUploader is name of asp.net file uploader control:

string strImgUploadedType = imgUploader.PostedFile.ContentType.ToString().ToLower();
string strImUploadedFileName = imgUploader.PostedFile.FileName;

//get Dimensions from stream
string strDim= getImageDimensions(imgUploader.PostedFile.InputStream);
//Or we can use from file
string strDim= getImageDimensions(imgUploader.PostedFile.FileName);

string[] strDimArr= s.Split(',');

Response.Write( "Image Width:" + strDimArr[0]+ “
”);
Response.Write("Image Height:" + strDimArr[1]+ “
”);


The PostedFile property will contain a valid System.Web.HttpPostedFile object if file indeed was uploaded. HttpPostedFile provides us with 4 properties:

* ContentLength: size of uploaded file in bytes
* ContentType: MIME type of uploaded file, i.e. "image/gif"
* FileName: full path to uploaded file on client's system, i.e.c:\Bin\Img1.gif
* InputStream: stream object that gives us access to uploaded data

No comments:

Post a Comment