C # upload images, add watermarks, and automatically generate thumbnail source code-2

Source: Internet
Author: User
Using System;
Using System. Data;
Using System. Data. SqlClient;
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. Text;
Using System. Text. RegularExpressions;
Using System. Drawing;
Using System. Drawing. Imaging;
Using System. Collections;
Using System. ComponentModel;
Namespace Legalsoft. Images
{
/// <Summary>
/// Summary of News
/// </Summary>
Public class XImage
{
Public Color tBackground;
Public Color tBorder;
Public Color tShadow;
Public int tQuality;
Public string markPosition;
/// <Summary>
/// Pre-define Image Parameters
/// </Summary>
Static Hashtable htmimes = new Hashtable ();
Internal readonly string AllowExt = ". jpe |. jpeg |. jpg |. png |. tif |. tiff |. bmp |. gif ";
Public XImage ()
{
TBackground = Color. Transparent;
TBorder = Color. Transparent;
TShadow = Color. Transparent;
TQuality = 100;
MarkPosition = "lower left corner ";
# Region image type pre-defined
Htmimes [". jpe"] = "image/jpeg ";
Htmimes [". jpeg"] = "image/jpeg ";
Htmimes [". jpg"] = "image/jpeg ";
Htmimes [". png"] = "image/png ";
Htmimes [". tif"] = "image/tiff ";
Htmimes [". tiff"] = "image/tiff ";
Htmimes [". bmp"] = "image/bmp ";
Htmimes [". gif"] = "image/gif ";
# Endregion
}
# Region download and save the specified URL Image
/// <Summary>
/// Download the file of the specified URL and save it to the specified directory
/// </Summary>
/// <Param name = "strurl"> </param>
Public void downloadimage (string strurl, string file)
{
System. net. WebClient WC = new system. net. WebClient ();
WC. downloadfile (strurl, file );
}
# Endregion
# Region C # automatically generate thumbnails
/// <Summary>
/// Determine the color based on the given name
/// </Summary>
/// <Param name = "name"> </param>
/// <Returns> </returns>
Public color tocolor (string name)
{
If (name = "white") return color. White;
If (name = "red") return color. Red;
If (name = "blue") return color. blue;
If (name = "green") return color. Green;
If (name = "Black") return Color. Black;
If (name = "gray") return Color. DarkGray;
If (name = "Yellow") return Color. Yellow;
If (name = "Purple") return Color. Cyan;
If (name = "colorless") return Color. Transparent;
Return Color. Transparent;
}
/// <Summary>
/// Set various colors by name, which can be expanded by yourself :)
/// </Summary>
/// <Param name = "name"> </param>
/// <Returns> </returns>
Public int ToQuality (string name)
{
Return Int32.Parse (name. Replace ("% ",""));
}
/// <Summary>
/// Obtain all relevant information of the image decoder
/// </Summary>
/// <Param name = "mimeType"> a string containing the multi-purpose Internet Mail Extension protocol (MIME) of the decoder </param>
/// <Returns> returns all information about the image decoder. </returns>
Private static ImageCodecInfo GetCodecInfo (string mimeType)
{
ImageCodecInfo [] CodecInfo = ImageCodecInfo. GetImageEncoders ();
Foreach (ImageCodecInfo ici in CodecInfo)
{
If (ici. MimeType = mimeType) return ici;
}
Return null;
}
/// <Summary>
/// Check the validity of the extension
/// </Summary>
/// <Param name = "sExt"> file name extension </param>
/// <Returns> If the extension is valid, true is returned; otherwise, false is returned. </returns>
Private bool CheckValidExt (string sExt)
{
Bool flag = false;
String [] aExt = AllowExt. Split ("| ");
Foreach (string filetype in aExt)
{
If (filetype. ToLower () = sExt)
{
Flag = true;
Break;
}
}
Return flag;
}
/// <Summary>
/// Save the image
/// </Summary>
/// <Param name = "image"> image object </param>
/// <Param name = "savepath"> Save path </param>
/// <Param name = "ICI"> codec parameters in the specified format </param>
Private void saveimage (system. Drawing. Image image, string savepath, imagecodecinfo ICI)
{
// Set the EncoderParameters object of the original image object
EncoderParameters parameters = new EncoderParameters (1 );
Parameters. Param [0] = new EncoderParameter (System. Drawing. Imaging. Encoder. Quality, (long) tQuality ));
Image. Save (savePath, ici, parameters );
Parameters. Dispose ();
}
/// <Summary>
/// Generate a thumbnail
/// </Summary>
/// <Param name = "sourceImagePath"> original image path (relative path) </param>
/// <Param name = "thumbnailImagePath"> the generated thumbnail path. If it is null, save it as the original image path (relative path). </param>
/// <Param name = "thumbnailImageWidth"> width of the thumbnail (the height is automatically generated based on the proportion of the source image) </param>
Public void ToThumbnail (string sourceImagePath, string thumbnailImagePath, int thumbnailImageWidth, int thumbnailImageHeight)
{
// 1. Check the image format and other information first
String ThumbnailImagePath = thumbnailImagePath;
String SourceImagePath = sourceImagePath;
String sExt = SourceImagePath. Substring (SourceImagePath. LastIndexOf ("."). ToLower ();
If (SourceImagePath. ToString () = System. String. Empty)
{
Throw new NullReferenceException ("SourceImagePath is null! ");
}
If (! CheckValidExt (sExt ))
{
Throw new ArgumentException ("the format of the original image file is incorrect. supported formats include [" + AllowExt + "]", "SourceImagePath ");
}
// Create an Image object from the original Image
System. Drawing. Image image = System. Drawing. Image. FromFile (HttpContext. Current. Server. MapPath (SourceImagePath ));
// 2. Calculate the position, size, and other information of the image.
Int tWidth, tHeight, tLeft, tTop;
Double fScale = (double) thumbnailImageHeight/(double) thumbnailImageWidth; // ratio of height to width
If (double) image. Width * fScale)> (double) image. Height) // if the source image is relatively wide
{
TWidth = thumbnailImageWidth;
THeight = (int) (double) image. Height * (double) tWidth/(double) image. Width );
TLeft = 0;
TTop = (thumbnailImageHeight-tHeight)/2;
}
Else
{
THeight = thumbnailImageHeight;
TWidth = (int) (double) image. Width * (double) tHeight/(double) image. Height );
TLeft = (thumbnailImageWidth-tWidth)/2;
TTop = 0;
}
If (tLeft <0) tLeft = 0;
If (tTop <0) tTop = 0;
If (tBorder! = Color. Transparent)
{
TWidth-= 2;
THeight-= 2;
TLeft ++;
TTop ++;
}
If (tShadow! = Color. Transparent)
{
TWidth-= 1;
THeight-= 1;
}
// Initialize a new Bitmap instance with the specified size and format
// Bitmap bitmap = new Bitmap (ThumbnailImageWidth, num, PixelFormat. Format32bppArgb );
Bitmap bitmap = new Bitmap (thumbnailImageWidth, thumbnailImageHeight, PixelFormat. Format32bppArgb );
// Create a new Graphics object from the specified Image object
Graphics graphics = Graphics. FromImage (bitmap );
// Clear the entire drawing surface and fill it with a transparent background color
If (tBackground! = Color. Transparent)
{
Graphics. Clear (tBackground );
}
Else
{
Graphics. Clear (Color. Transparent );
}
// Add a shadow
If (tShadow! = Color. Transparent)
{
Pen shPen = new Pen (tShadow );
Graphics. DrawLine (shPen, new Point (1, thumbnailImageHeight-1), new Point (thumbnailImageWidth-1, thumbnailImageHeight-1 ));
Graphics. DrawLine (shPen, new Point (thumbnailImageWidth-1, 1), new Point (thumbnailImageWidth-1, thumbnailImageHeight-1 ));
}
// Add a border
If (tborder! = Color. Transparent)
{
Pen bdpen = new pen (tborder );
If (tshadow! = Color. Transparent)
{
Graphics. drawrectangle (bdpen, new rectangle (0, 0, thumbnailImageWidth-2, thumbnailImageHeight-2 ));
}
Else
{
Graphics. drawrectangle (bdpen, new rectangle (0, 0, thumbnailImageWidth-1, thumbnailImageHeight-1 ));
}
}
// Draw the original image object at the specified position and by the specified size
Graphics. DrawImage (image, new Rectangle (tLeft, tTop, tWidth, tHeight ));
Image. Dispose ();
Try
{
// Save the original image in the specified format and use the specified codec parameter to the specified file
String savepath = (ThumbnailImagePath = null? SourceImagePath: ThumbnailImagePath );
SaveImage (bitmap, HttpContext. Current. Server. MapPath (savepath), GetCodecInfo (string) htmimes [sExt]);
}
Catch (system. Exception E)
{
Throw E;
}
Finally
{
Bitmap. Dispose ();
Graphics. Dispose ();
}
}
# Endregion
# Region C # Add a watermark to an image
Public void mark (string sourceimagepath, string markstring)
{
// 1. Check the image format and other information first
String markimagepath = sourceimagepath;
String sourceimagepath = sourceimagepath;
String sext = sourceimagepath. substring (sourceimagepath. lastindexof ("."). tolower ();
If (sourceimagepath. tostring () = system. String. Empty)
{
Throw new nullreferenceexception ("sourceimagepath is null! ");
}
If (! Checkvalidext (sext ))
{
Throw new argumentexception ("the format of the original image file is incorrect. supported formats include [" + allowext + "]", "sourceimagepath ");
}
// Create an Image object from the original Image
System. Drawing. Image image = System. Drawing. Image. FromFile (HttpContext. Current. Server. MapPath (SourceImagePath ));
// Initialize a new Bitmap instance with the specified size and format
Bitmap bitmap = new Bitmap (image. Width, image. Height, PixelFormat. Format32bppArgb );
// Create a new Graphics object from the specified Image object
Graphics graphics = Graphics. FromImage (bitmap );
// Draw the original image object at the specified position and by the specified size
Graphics. DrawImage (image, new Rectangle (0, 0, image. Width, image. Height ));
# Region watermark
// Set the watermark font
Int fHeight = image. Height/5;
If (fHeight> 16) fHeight = 16;
Font drawFont = new Font ("Arial", fHeight );
// Set the watermark text position, which is in the lower left corner by default
Float x = 4;
Float y = image. Height-drawfont. Height-4;
If (markposition = "upper left corner ")
{
Y = 4;
}
If (markposition = "upper right corner ")
{
X = image. Width-markstring. length * fheight/2-fheight;
Y = 4;
}
If (markPosition = "bottom right corner ")
{
X = image. Width-markString. Length * fHeight/2-fHeight;
}
If (markPosition = "image Center ")
{
X = image. Width/2-markString. Length * fHeight/2;
Y = image. Height/2-fHeight/2;
}
StringFormat drawFormat = new StringFormat ();
DrawFormat. FormatFlags = StringFormatFlags. NoWrap;
// Set the watermark text color. First, draw a black word as the shadow and then draw a white word, which is conspicuous;
SolidBrush drawBrush = new SolidBrush (Color. Black );
Graphics. DrawString (markString, drawFont, drawBrush, x, y, drawFormat );
DrawBrush. Color = Color. White;
Graphics. DrawString (markString, drawFont, drawBrush, x-1, Y-1, drawFormat );
# Endregion
Image. Dispose ();
Try
{
// Save the original image in the specified format and use the specified codec parameter to the specified file
String savepath = SourceImagePath;
Saveimage (bitmap, httpcontext. Current. server. mappath (savepath), getcodecinfo (string) htmimes [sext]);
}
Catch (system. Exception E)
{
Throw E;
}
Finally
{
Bitmap. Dispose ();
Graphics. Dispose ();
}
}
# Endregion
}
}
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.