Asp.net uploads and generates a thumbnail, text watermark, and image watermark.

Source: Internet
Author: User
Tags bmp image

Method 1

Using System;
Using System. Data;
Using System. Configuration;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;
Using System. IO;

Public partial class _ Default: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{

}
Protected void button#click (object sender, EventArgs e)
{
If (FileUpload1.HasFile)
{
String fileContentType = FileUpload1.PostedFile. ContentType;
If (fileContentType = "image/bmp" | fileContentType = "image/gif" | fileContentType = "image/pjpeg ")
{
String name = FileUpload1.PostedFile. FileName; // client file path

FileInfo file = new FileInfo (name );
String fileName = file. Name; // file Name
String fileName_s = "s _" + file. Name; // The Name Of The thumbnail file.
String fileName_sy = "sy _" + file. Name; // watermark image file Name (text)
String fileName_syp = "syp _" + file. Name; // watermark image file Name (image)
String webFilePath = Server. MapPath ("file/" + fileName); // Server-side file path
String webFilePath_s = Server. MapPath ("luepu/" + fileName_s); // Server-side thumbnail path
// String webFilePath_sy = Server. MapPath ("file/" + fileName_sy); // watermark path (text) on the Server)
// String webFilePath_syp = Server. MapPath ("file/" + fileName_syp); // watermark path (image) on the Server)
// String webFilePath_sypf = Server. MapPath ("file/1.jpg"); // Server-side watermark image path (image)

If (! File. Exists (webFilePath ))
{
Try
{
FileUpload1.SaveAs (webFilePath); // use the SaveAs method to save the file
// AddShuiYinWord (webFilePath, webFilePath_sy );
// AddShuiYinPic (webFilePath, webFilePath_syp, webFilePath_sypf );
MakeThumbnail (webFilePath, webFilePath_s, 392,203, "Cut"); // method for generating thumbnails
Label1.Text = "prompt: the file" "+ fileName +" "is uploaded successfully, and a" + fileName_s + "thumbnail is generated. The file type is" + FileUpload1.PostedFile. contentType + ", file size:" + FileUpload1.PostedFile. contentLength + "B ";
}
Catch (Exception ex)
{
Label1.Text = "prompt: File Upload Failed. cause of failure:" + ex. Message;
}
}
Else
{
Label1.Text = "prompt: The file already exists. Please rename it and upload it ";
}
}
Else
{
Label1.Text = "prompt: the file type does not match ";
}
}
}

/**/
/**/
/// <Summary>
/// Generate a thumbnail
/// </Summary>
/// <Param name = "originalImagePath"> source image path (physical path) </param>
/// <Param name = "thumbnailPath"> thumbnail path (physical path) </param>
/// <Param name = "width"> thumbnail width </param>
/// <Param name = "height"> thumbnail height </param>
/// <Param name = "mode"> how to generate a thumbnail </param>
Public static void MakeThumbnail (string originalImagePath, string thumbnailPath, int width, int height, string mode)
{
System. Drawing. Image originalImage = System. Drawing. Image. FromFile (originalImagePath );

Int towidth = width;
Int toheight = height;

Int x = 0;
Int y = 0;
Int ow = originalImage. Width;
Int oh = originalImage. Height;

Switch (mode)
{
Case "HW": // specify high-width Scaling (possibly deformed)
Break;
Case "W": // specify the width, and the height is proportional.
Toheight = originalImage. Height * width/originalImage. Width;
Break;
Case "H": // specify the height. The width is proportional.
Towidth = originalImage. Width * height/originalImage. Height;
Break;
Case "Cut": // specify the height and width (not deformed)
If (double) originalImage. Width/(double) originalImage. Height> (double) towidth/(double) toheight)
{
Oh = originalImage. Height;
Ow = originalImage. Height * towidth/toheight;
Y = 0;
X = (originalImage. Width-ow)/2;
}
Else
{
Ow = originalImage. Width;
Oh = originalImage. Width * height/towidth;
X = 0;
Y = (originalImage. Height-oh)/2;
}
Break;
Default:
Break;
}

// Create a bmp Image
System. Drawing. Image bitmap = new System. Drawing. Bitmap (towidth, toheight );

// Create a canvas
System. Drawing. Graphics g = System. Drawing. Graphics. FromImage (bitmap );

// Set a high quality Interpolation Method
G. InterpolationMode = System. Drawing. Drawing2D. InterpolationMode. High;

// Set high quality and smooth Low Speed
G. SmoothingMode = System. Drawing. Drawing2D. SmoothingMode. HighQuality;

// Clear the canvas and fill it with a transparent background color
G. Clear (System. Drawing. Color. Transparent );

// Draw the specified part of the original image at the specified position and in the specified size
G. DrawImage (originalImage, new System. Drawing. Rectangle (0, 0, towidth, toheight ),
New System. Drawing. Rectangle (x, y, ow, oh ),
System. Drawing. GraphicsUnit. Pixel );

Try
{
// Save the thumbnail in jpg format
Bitmap. Save (thumbnailPath, System. Drawing. Imaging. ImageFormat. Jpeg );
}
Catch (System. Exception e)
{
Throw e;
}
Finally
{
OriginalImage. Dispose ();
Bitmap. Dispose ();
G. Dispose ();
}
}

/**/
/**/
/**/
/// <Summary>
/// Add a text watermark to the image
/// </Summary>
/// <Param name = "Path"> original server image Path </param>
/// <Param name = "Path_sy"> generated image path with a text watermark </param>
Protected void AddShuiYinWord (string Path, string Path_sy)
{
String addText = "test watermark ";
System. Drawing. Image image = System. Drawing. Image. FromFile (Path );
System. Drawing. Graphics g = System. Drawing. Graphics. FromImage (image );
G. DrawImage (image, 0, 0, image. Width, image. Height );
System. Drawing. Font f = new System. Drawing. Font ("Verdana", 16 );
System. Drawing. Brush B = new System. Drawing. SolidBrush (System. Drawing. Color. Blue );

G. DrawString (addText, f, B, 15, 15 );
G. Dispose ();

Image. Save (Path_sy );
Image. Dispose ();
}

/**/
/**/
/**/
/// <Summary>
/// Generate an image watermark on the Image
/// </Summary>
/// <Param name = "Path"> original server image Path </param>
/// <Param name = "Path_syp"> path of the image watermark generated </param>
/// <Param name = "Path_sypf"> watermark image path </param>
Protected void AddShuiYinPic (string Path, string Path_syp, string Path_sypf)
{
System. Drawing. Image image = System. Drawing. Image. FromFile (Path );
System. Drawing. Image copyImage = System. Drawing. Image. FromFile (Path_sypf );
System. Drawing. Graphics g = System. Drawing. Graphics. FromImage (image );
G. drawImage (copyImage, new System. drawing. rectangle (image. width-copyImage. width, image. height-copyImage. height, copyImage. width, copyImage. height), 0, 0, copyImage. width, copyImage. height, System. drawing. graphicsUnit. pixel );
G. Dispose ();

Image. Save (Path_syp );
Image. Dispose ();
}
}

 

 

Method 2

ImageThumbnail. cs generic class

Using System;
Using System. IO;
Using System. Drawing;
Using System. Drawing. Imaging;

Public class ImageThumbnail
{
Public Image ResourceImage;
Private int ImageWidth;
Private int ImageHeight;
Public string ErrorMessage;

Public ImageThumbnail (string ImageFileName)
{
ResourceImage = Image. FromFile (ImageFileName );
ErrorMessage = "";
}

Public bool ThumbnailCallback ()
{
Return false;
}

// Method 1, by size
Public bool performancedimage (int Width, int Height, string targetFilePath)
{
Try
{
Image cecedimage;
Image. GetThumbnailImageAbort callb = new Image. GetThumbnailImageAbort (ThumbnailCallback );
Performancedimage = ResourceImage. GetThumbnailImage (Width, Height, callb, IntPtr. Zero );
Performancedimage. Save (@ targetFilePath, ImageFormat. Jpeg );
Cecedimage. Dispose ();
Return true;
}
Catch (Exception e)
{
ErrorMessage = e. Message;
Return false;
}
}

// Method 2, scale down by percentage by 60% Percent to 0.6 targetFilePath as the target path
Public bool performancedimageprecent (double Percent, string targetFilePath)
{
Try
{
Image cecedimage;
Image. GetThumbnailImageAbort callb = new Image. GetThumbnailImageAbort (ThumbnailCallback );
ImageWidth = Convert. ToInt32 (ResourceImage. Width * Percent );
ImageHeight = (ResourceImage. Height) * ImageWidth/ResourceImage. Width; // proportional Scaling
Performancedimage = ResourceImage. GetThumbnailImage (ImageWidth, ImageHeight, callb, IntPtr. Zero );
Performancedimage. Save (@ targetFilePath, ImageFormat. Jpeg );
Cecedimage. Dispose ();
Return true;
}
Catch (Exception e)
{
ErrorMessage = e. Message;
Return false;
}
}
}

 

 

Default2.aspx

<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "Default2.aspx. cs" Inherits = "Default2" %>

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> No title page </title>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
& Nbsp; <asp: FileUpload ID = "FileUpload1" runat = "server"/>
<Asp: Button ID = "Button1" runat = "server" OnClick = "button#click" Text = "Button"/>
<Asp: Label ID = "Label1" runat = "server" ForeColor = "# C00000"> </asp: Label>
& Nbsp; <br/>
<Asp: Label ID = "Label2" Visible = "false" runat = "server" Text = "source image"> </asp: Label> <asp: image ID = "Image1" runat = "server" Visible = "false"/>
<Asp: Label ID = "Label3" Visible = "false" runat = "server" Text = "proportional thumbnail"> </asp: Label> <asp: image ID = "Image2" runat = "server" Visible = "false"/> <br/>
<Br/>
</Div>
</Form>
</Body>
</Html>

 

Default2.aspx. cs

Using System;
Using System. Data;
Using System. Configuration;
Using System. Collections;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;
Using System. Drawing;
Using System. Drawing. Imaging;
Using System. Drawing. Drawing2D;
Using System. IO;

Public partial class Default2: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{

}
Protected void button#click (object sender, EventArgs e)
{
Try
{
If (FileUpload1.PostedFile. FileName = "")
{
This. Label1.Text = "select a file! ";
This. Image1.Visible = false;
This. Image2.Visible = false;
This. Label2.Visible = false;
This. Label3.Visible = false;
}
Else
{
String filepath = FileUpload1.PostedFile. FileName;
String filename = filepath. Substring (filepath. LastIndexOf ("\") + 1 );
String serverpath1 = Server. MapPath ("images/") + filename;
String serverpath2 = Server. MapPath ("luepu/") + System. DateTime. Now. ToString ("yyyyMMddhhmmss") + filename;
String strUrl = serverpath2.Substring (serverpath2.LastIndexOf ("\") + 1 );
FileUpload1.PostedFile. SaveAs (serverpath1 );
ImageThumbnail img = new ImageThumbnail (filepath );
Img. performancedimageprecent (0.4, serverpath2); // 0.4 indicates a 40% reduction
This. Label1.Text = "Upload successful! ";
This. Image1.Visible = true;
This. Image2.Visible = true;
This. Label2.Visible = true;
This. Label3.Visible = true;
This. Image1.ImageUrl = "images/" + filename;
This. Image2.ImageUrl = "luepu/" + strUrl;

}
}
Catch (Exception error)
{
This. Label1.Text = "Upload error! Cause: "+ error. ToString ();
This. Image1.Visible = false;
This. Image2.Visible = false;
This. Label2.Visible = false;
This. Label3.Visible = false;

}
}

}

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.