|
Back
Uploading an Image File, then Creating a Thumbnail Version of it on File
The following code uploads a jpg file, saves it to a directory on the web server, and then creates a thumbnail of it and saves that thumbnail to another directory.
This could be better method than creating a thumbnail of the image on the fly when a user requests that image since it only processes the thumbnail once. If your web site has a large amount of images it is preferable to save the thumbnail to file and then display it as required - less processing required and potentially faster delivery.
The method for uploading the file is:
public void WriteToFile(string strPath, byte[] Buffer) { // Create a file FileStream newFile = new FileStream(strPath, FileMode.Create);
// Write data to the file newFile.Write(Buffer, 0, Buffer.Length);
// Close file newFile.Close(); }
The method(s) for creating the thumbnail of the image are:
public void CreateThumbnail(string FileLocation) { // create an image object, using the filename we just retrieved System.Drawing.Image image = System.Drawing.Image.FromFile(FileLocation);
// create the actual thumbnail image System.Drawing.Image thumbnailImage = image.GetThumbnailImage(128, 128, new System.Drawing.Image.GetThumbnailImageAbort(this.ThumbnailCallback), IntPtr.Zero);
// make a memory stream to work with the image bytes MemoryStream imageStream = new MemoryStream();
// put the image into the memory stream thumbnailImage.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
// make byte array the same size as the image byte[] imageContent = new Byte[imageStream.Length];
// rewind the memory stream imageStream.Position = 0;
// load the byte array with the image imageStream.Read(imageContent, 0, (int)imageStream.Length);
// create the thumbnail using the write to file method above this.WriteToFile("c:/thumb.jpg", imageContent);
}
public bool ThumbnailCallback() { return true; }
You will need to ensure the following using statements are included:
using System; using System.IO;
You then need to add a file upload form object to your page and in this case call it img1. The following code checks that an image has been selected, and then checks that it is a jpg before uploading the file and then creating a thumbnail of it.
string fileName1;
// Upload image 1 if ((img1.PostedFile != null) && (img1.PostedFile.ContentLength > 0)) { if (img1.PostedFile.ContentType.ToString() == "image/pjpeg") { HttpPostedFile myFile1 = this.img1.PostedFile; fileName1 = System.IO.Path.GetFileName(img1.PostedFile.FileName); int nFileLen = myFile1.ContentLength; byte[] myData = new byte[nFileLen]; myFile1.InputStream.Read(myData, 0, nFileLen);
WriteToFile("c:/temp/" + fileName1, myData); CreateThumbnail("c:/temp/" + fileName1);
} else { // NB The image wasn't a jpg - notify the user
} } else { // NB No file selected - notify the user }
Back
|