Friday, October 9, 2009

Generating thumbnail of an image on the fly and saving it to the server.

Yup, yet another scenario where I fumed my mind. I was with a product catalogue application, for a POC (Proof of concept) to Malaysian client, where the registered users would be able to add a product details under a chosen category. The uploaded products will be listed in the home page based up on the category. Requirement was of very low complexity.

File upload control is quite enough to upload a file in the server, which was serving the basic of my yesterday’s requirement. The product listing page, for sure, has to show the thumbnail view of the images. The product images which the client was supplied where of huge size. (1024X768 kind of stuff). No wonder, I was allowed to have only a single file upload control in the page. I just started bending the chair behind, how do I have a thumbnail image with the same name of the parent image, in a different folder.

Didn’t take much time to get out of the problem, ASP.Net System.Drawing namespace is what we need to have to get this done.

Upload an image in to server with the file upload control. (Say a 1024X768 sized image)

Generate random number generated from C# to give a unique name for the file which is going to be saved in the server. Generate the thumbnail image by specifying the width and height.

private void UploadImage()
{
if (UploadImage.HasFile) {
try {
Random random = new Random();
int randumNumber = random.Next(1000);
string FolderPath = Server.MapPath("~") + "\\ProductImages\\";
string FileName = randumNumber.ToString() + "-" + UploadImage.FileName;
System.Drawing.Image myImage = System.Drawing.Image.FromStream(UploadImage.PostedFile.InputStream);

System.Drawing.Image thumbnailImage = myImage.GetThumbnailImage(64, 64, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

thumbnailImage.Save(FolderPath + "/thumbnails/" + FileName, System.Drawing.Imaging.ImageFormat.Gif); //thumbnails in different folder

UploadImage.SaveAs(FolderPath + "/" + FileName);
}
catch
{
MessageLabel.Text = "Unable to save the file";
}

public bool ThumbnailCallback()
{
return false;
}

Thinks are simple once you have a try, until then it would be complex. Now my concern is to have a water mark of the company logo on the main image on the fly. Come down,

Genrating Watermark on the fly

private void MakeWatermark()

{

string sProduct = Server.MapPath("ProductImage.jpg”);
string sLogo = Server.MapPath("logo.gif");

System.Drawing.Image oImage= Bitmap.FromFile(sProduct);
Graphics oGraphics = Graphics.FromImage(sLogo);
Bitmap oLogo = new Bitmap(s2);
oGraphics.DrawImage(oLogo, new Point(70, 70));

Response.ContentType = "image/JPEG";
oImage.Save(Response.OutputStream, ImageFormat.Jpeg);

}