To upload a picture in asp.net and generate a thumbnail, you can refer to the following code:
private void Btnuploadpicture_click (object sender, System.EventArgs e)
{
Check that the upload file is in a valid format
if (this. UploadFile.PostedFile.ContentType.ToLower (). IndexOf ("image") < 0)
{
Response.Write ("Upload picture format is invalid!") ");
Return
}
Generate artwork
byte[] Ofilebyte = new Byte[this. UploadFile.PostedFile.ContentLength];
System.IO.Stream ostream = this. UploadFile.PostedFile.InputStream;
System.Drawing.Image oimage = System.Drawing.Image.FromStream (ostream);
int owidth = Oimage.width; Width of original artwork
int oheight = Oimage.height; Height of original artwork
int twidth = 100; Set the initial width of the thumbnail
int theight = 100; Set the initial height of the thumbnail
Calculate the width and height of the thumbnail proportionally
if (owidth >= oheight)
{
Theight = (int) Math.floor (convert.todouble (oheight) * (Convert.todouble (twidth)
/convert.todouble (Owidth)));
}
Else
{
Twidth = (int) Math.floor (convert.todouble (owidth) * (Convert.todouble (theight)
/convert.todouble (Oheight)));
}
Generate thumbnail artwork
Bitmap timage = new Bitmap (twidth,theight);
Graphics g = graphics.fromimage (timage);
G.interpolationmode = System.Drawing.Drawing2D.InterpolationMode.High;
Set high quality interpolation method
G.smoothingmode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
Set high quality, low speed rendering smooth degree
G.clear (color.transparent); Empty the canvas and fill with a transparent background color
G.drawimage (oimage,new Rectangle (0,0,twidth,theight),
New Rectangle (0,0,owidth,oheight), graphicsunit.pixel);
String ofullname = Server.MapPath (".") + "/" + "O" +
DateTime.Now.ToShortDateString (). Replace ("-", "") + DateTime.Now.Hour.ToString ()
+ DateTime.Now.Minute.ToString () + DateTime.Now.Second.ToString ()
+ DateTime.Now.Millisecond.ToString () + ". jpg"; Save the physical path of the original artwork
String tfullname = Server.MapPath (".") + "/" + "T" +
DateTime.Now.ToShortDateString (). Replace ("-", "") + DateTime.Now.Hour.ToString ()
+ DateTime.Now.Minute.ToString () + DateTime.Now.Second.ToString ()
+ DateTime.Now.Millisecond.ToString () + ". jpg"; Save the physical path of the thumbnail
Try
{
Save pictures in jpg format
Oimage.save (Ofullname,system.drawing.imaging.imageformat.jpeg);
Timage.save (Tfullname,system.drawing.imaging.imageformat.jpeg);
}
catch (Exception ex)
{
Throw ex;
}
Finally
{
Releasing resources
Oimage.dispose ();
G.dispose ();
Timage.dispose ();
}
}