Saturday, May 23, 2009

Creating Runtime Image Thumbnail (Asp.NET)



Upload an image and create thumbnail at runtime in ASP.NET


protected void btnUpload_Click(object sender, EventArgs e)
{
//string _fileExtension = VirtualPathUtility.GetExtension(UploadPhoto.PostedFile.FileName);
string _fileExtension = UploadPhoto.PostedFile.FileName.Substring(UploadPhoto.PostedFile.FileName.LastIndexOf('.'));
if (_fileExtension != ".jpg" && _fileExtension != ".gif" && _fileExtension != ".bmp" && _fileExtension != ".png")
{
ltScript.Text = "Please upload images(jpeg/gif/bmp/png) files";
return;
}

int _filesize = UploadPhoto.FileBytes.Length;
if(_filesize>200000)
{
ltScript.Text="Size exeeds the limit of 200 KB, please upload a file with size of maximum 200 KB";
return;
}
FileUpload userImage = (FileUpload)UploadPhoto;
Byte[] imgByte = null;
Byte[] _thumbByte = null;
if (userImage.HasFile && userImage.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = UploadPhoto.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
_thumbByte = GetThumbnail();

DatabaseAdapter _dataadapt = new DatabaseAdapter();
_dataadapt.UpdateUserPhoto(ID, imgByte, _thumbByte);

}
ltScript.Text = "File has been uploaded...";

}
private Byte[] GetThumbnail()
{
//Creating Thumbnail method
System.Drawing.Image _image = System.Drawing.Image.FromStream
(UploadPhoto.PostedFile.InputStream);
float imgWidth = _image.PhysicalDimension.Width;
float imgHeight = _image.PhysicalDimension.Height;
float imgSize = imgHeight > imgWidth ? imgHeight : imgWidth;

//the approximately pixel size of thumbnail image is 100 x 100 based on ratio
float imgResize = imgSize <= 100 ? (float)1.0 : 100 / imgSize;
imgWidth *= imgResize; imgHeight *= imgResize;
//generating the thumbnail
System.Drawing.Image _thumbnail = _image.GetThumbnailImage((int)imgWidth, (int)imgHeight, delegate() { return false; }, (IntPtr)0);

// Converting Image File to byte Array
byte[] imgBytes = null;
try
{
using (MemoryStream ms = new MemoryStream())
{
_thumbnail.Save(ms, ImageFormat.Jpeg);
imgBytes = ms.ToArray();
}
}
catch (Exception ex) { ltLabel.Text = ex.ToString(); }
return imgBytes;
}

No comments:

Post a Comment