C# source code for uploading images and generating thumbnails in ASP.NET<FONT size=4><FONT size=4><FONT size=4>using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
namespace eMeng.Exam
{
/// <summary>
/// Summary description of Thumbnail.
/// </summary>
public class Thumbnail : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.WebControls.Button Button1;
private void Page_Load(object sender, System.EventArgs e)
{
//Put user code here to initialize the page
Label1.Text = "<h3>Easy to practice in ASP.NET?lt;/h3>";
Button1.Text = "Upload and display thumbnails";
}
#region Code generated by Web Form Designer
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Forms designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Designer supports required methods - do not use code editor to modify
/// The content of this method.
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void Button1_Click(object sender, System.EventArgs e)
{
HttpFileCollection MyFileColl = HttpContext.Current.Request.Files;
HttpPostedFile MyPostedFile = MyFileColl[0];
if (MyPostedFile.ContentType.ToString().ToLower().IndexOf("image") < 0)
{
Response.Write("Invalid graphic format.");
return;
}
GetThumbNail(MyPostedFile.FileName, 100, 100,
MyPostedFile.ContentType.ToString(), false, MyPostedFile.InputStream);
}
private System.Drawing.Imaging.ImageFormat GetImageType(object strContentType)
{
if ((strContentType.ToString().ToLower()) == "image/pjpeg")
{
return System.Drawing.Imaging.ImageFormat.Jpeg;
}
else if ((strContentType.ToString().ToLower()) == "image/gif")
{
return System.Drawing.Imaging.ImageFormat.Gif;
}
else if ((strContentType.ToString().ToLower()) == "image/bmp")
{
return System.Drawing.Imaging.ImageFormat.Bmp;
}
else if ((strContentType.ToString().ToLower()) == "image/tiff")
{
return System.Drawing.Imaging.ImageFormat.Tiff;
}
else if ((strContentType.ToString().ToLower()) == "image/x-icon")
{
return System.Drawing.Imaging.ImageFormat.Icon;
}
else if ((strContentType.ToString().ToLower()) == "image/x-png")
{
return System.Drawing.Imaging.ImageFormat.Png;
}
else if ((strContentType.ToString().ToLower()) == "image/x-emf")
{
return System.Drawing.Imaging.ImageFormat.Emf;
}
else if ((strContentType.ToString().ToLower()) == "image/x-exif")
{
return System.Drawing.Imaging.ImageFormat.Exif;
}
else if ((strContentType.ToString().ToLower()) == "image/x-wmf")
{
return System.Drawing.Imaging.ImageFormat.Wmf;
}
else
{
return System.Drawing.Imaging.ImageFormat.MemoryBmp;
}
}
private void GetThumbNail(string strFileName, int iWidth, int iheight,
string strContentType, bool blnGetFromFile, System.IO.Stream ImgStream)
{
System.Drawing.Image oImg;
if (blnGetFromFile)
{
oImg = System.Drawing.Image.FromFile(strFileName);
}
else
{
oImg = System.Drawing.Image.FromStream(ImgStream);
}
oImg = oImg.GetThumbnailImage(iWidth, iheight, null, IntPtr.Zero);
string strGuid = System.Guid.NewGuid().ToString().ToUpper();
string strFileExt = strFileName.Substring(strFileName.LastIndexOf("."));
Response.ContentType = strContentType;
MemoryStream MemStream = new MemoryStream();
oImg.Save(MemStream, GetImageType(strContentType));
MemStream.WriteTo(Response.OutputStream);
}
}
}
</FONT></FONT></FONT><FONT color=#ff0000 size=4></FONT><FONT size=4>Function:
1. Upload the image file (JPG GIF PNG),
2. Save to the specified path (set the path in web.config and save the file in its original format),
3. And automatically generate the specified width (set the width in web.config)
4. and specified format (specify the thumbnail format in web.config)
5. A thumbnail with the same proportions as the original image (the height of the thumbnail is calculated based on the width and the width and height of the original image)
6. Can determine whether the file already exists
7. If not overridden, an error is given
8. If the "Overwrite original image" checkbox is selected, the original image will be overwritten.
9. According to requirements, more than one file input and corresponding checkbox can be set on the webform.
10. And after the file is uploaded, the file name, size, bytes, and
11. The file name size of the thumbnail.
12. The file name format of thumbnails: original image + "_thumb." + specified format, such as: test.jpg_thumb.gif, for easy management.
-------------------
public void UploadFile(object sender, System.EventArgs e)
{
string imgNameOnly, imgNameNoExt, imgExt;
string imgThumbnail;
int errorNumber = 0;
System.Drawing.Image oriImg, newImg;
string strFePicSavePath = ConfigurationSettings.AppSettings["FePicSavePath"].ToString();
string strFePicThumbFormat = ConfigurationSettings.AppSettings["FePicThumbFormat"].ToString().ToLower();
int intFeThumbWidth = Int32.Parse(ConfigurationSettings.AppSettings["FePicThumbWidth"]);
string fileExt;
StringBuilder picInfo = new StringBuilder();
if(Page.IsValid)
{
for(int i = 0;i < Request.Files.Count; i++)
{
HttpPostedFile PostedFile = Request.Files[i];
fileExt = (System.IO.Path.GetExtension(PostedFile.FileName)).ToString().ToLower();
imgNameOnly = System.IO.Path.GetFileName(PostedFile.FileName);
if(fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".png")
{
if(System.IO.File.Exists(strFePicSavePath + imgNameOnly) && (checkboxlistRewrite.Items[i].Selected == false))
{
erroNumber = erroNumber + 1;
picInfo.Append("<b>Error:</b>File("+ (i+1) +") " + imgNameOnly + " already exists, please change the file name<br/>" );
}
}
else
{
erroNumber = erroNumber + 1;
picInfo.Append("<b>Error:</b> file("+ (i+1) +") " + imgNameOnly + " extension" + fileExt + " not allowed<br/>" );
}
}
if(erroNumber > 0)
{
picInfo.Append("<font color=red>All operations are not completed, please correct the errors and proceed again</font><br/>");
}
else
{
for(int i = 0;i < Request.Files.Count; i++)
{
HttpPostedFile PostedFile = Request.Files[i];
imgNameOnly = System.IO.Path.GetFileName(PostedFile.FileName);
imgNameNoExt = System.IO.Path.GetFileNameWithoutExtension(PostedFile.FileName);
imgExt = System.IO.Path.GetExtension(PostedFile.FileName).ToString().ToLower();
oriImg = System.Drawing.Image.FromStream(PostedFile.InputStream);
newImg = oriImg.GetThumbnailImage(intFeThumbWidth, intFeThumbWidth * oriImg.Height/oriImg.Width,null,new System.IntPtr(0));
switch(imgExt)
{
//case ".jpeg":
case ".jpg":
oriImg.Save(strFePicSavePath + imgNameOnly , System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case ".gif":
oriImg.Save(strFePicSavePath + imgNameOnly , System.Drawing.Imaging.ImageFormat.Gif);
break;
case ".png":
oriImg.Save(strFePicSavePath + imgNameOnly , System.Drawing.Imaging.ImageFormat.Png);
break;
}
//oriImg.Save(ConfigurationSettings.AppSettings["FePicSavePath"] + imgNameNoExt + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
switch(strFePicThumbFormat)
{
//jpeg format can get the smallest file size, and the png is the largest size
//case "jpeg":
case "jpg":
newImg.Save(strFePicSavePath + imgNameOnly + "_thumb.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
imgThumbnail = imgNameOnly + "_thumb.jpg";
break;
case "gif":
newImg.Save(strFePicSavePath + imgNameOnly + "_thumb.gif",System.Drawing.Imaging.ImageFormat.Gif);
imgThumbnail = imgNameOnly + "_thumb.gif";
break;
case "png":
newImg.Save(strFePicSavePath + imgNameOnly + "_thumb.png",System.Drawing.Imaging.ImageFormat.Png);
imgThumbnail = imgNameOnly + "_thumb.png";
break;
default:
newImg.Save(strFePicSavePath + imgNameOnly + "_thumb.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
imgThumbnail = imgNameOnly + "_thumb.jpg";
break;
}//switch
picInfo.Append("<b>File name:</b>" + imgNameOnly + " ( " + oriImg.Width + " x " + oriImg.Height + " ) " + PostedFile.ContentLength/1024 + "KB<br/>");
picInfo.Append("<b>Thumbnail name:</b>" + imgThumbnail + " ( " + newImg.Width + " x " + newImg.Height + " )<br/><br/>");
oriImg .Dispose();
newImg.Dispose();
}//for
picInfo.Append("<font color=red>All operations successful</font><br/>");
}// if erronumber = 0
}
else
{
picInfo.Append("<font color=red>There is an error, please check. The operation was not successful</font><br/>");
}
lblPicInfo.Text = picInfo.ToString();
}
</FONT>