C # Add watermark code to picture

Source: Internet
Author: User
Tags relative

Using System;
Using System.IO;
Using System.Collections;
Using System.Drawing;
Using System.Drawing.Drawing2D;
Using System.Drawing.Imaging;

Namespace Imag_writer
{
<summary>
Type of watermark
</summary>
public enum Watermarktype
{
<summary>
Text watermark
</summary>
Textmark,
<summary>
Picture watermark
</summary>
ImageMark//Temporarily only add text watermark
};

<summary>
The location of the watermark
</summary>
public enum Watermarkposition
{
<summary>
Upper left corner
</summary>
Wmp_left_top,
<summary>
Lower left corner
</summary>
Wmp_left_bottom,
<summary>
Top right corner
</summary>
Wmp_right_top,
<summary>
Lower right corner
</summary>
Wmp_right_bottom
};

<summary>
Classes that work with pictures (including watermark, generating thumbnails)
</summary>
public class Imagewatermark
{
Public Imagewatermark ()
{
//
TODO: Add constructor logic here
//
}

#region to add a watermark to a picture
<summary>
Add watermark (two kinds of image watermark and text watermark)
</summary>
<param name= "OldPath" > Original picture absolute address </param>
<param name= "NewPath" > New picture placement Absolute address </param>
<param name= "Wmttype" > Type of watermark to add </param>
<param name= "swatermarkcontent" > Watermark content, if you add a text watermark, this is the text to be added;
To add a picture watermark, this is the path to the picture </param>
public void Addwatermark (string oldpath, String NewPath,
Watermarktype Wmttype, String swatermarkcontent)
{
Try
{
Image image = Image.FromFile (OldPath);

Bitmap B = new Bitmap (image. Width, image. Height,
PIXELFORMAT.FORMAT24BPPRGB);

Graphics g = graphics.fromimage (b);
G.clear (Color.White);
G.smoothingmode = smoothingmode.highquality;
G.interpolationmode = Interpolationmode.high;

G.drawimage (image, 0, 0, image. Width, image. Height);

Switch (wmttype)
{

Case Watermarktype.textmark:
Text watermark
This.addwatermarktext (g, Swatermarkcontent, "Wm_bottom_right",
Image. Width, image. Height);
Break
}

B.save (NewPath);
B.dispose ();
Image. Dispose ();
}
Catch
{
if (file.exists (OldPath))
{
File.delete (OldPath);
}
}
Finally
{
if (file.exists (OldPath))
{
File.delete (OldPath);
}
}
}

<summary>
Add watermark Text
</summary>
<param name= "Picture" >imge object </param>
<param name= "_watermarktext" > Watermark text content </param>
<param name= "_watermarkposition" > Watermark location </param>
<param name= "_width" > Added watermark picture width </param>
<param name= "_height" > Added watermark Picture High </param>
private void Addwatermarktext (Graphics picture, String _watermarktext,
string _watermarkposition, int _width, int _height)
{
Determines the font size of the watermark text
Int[] sizes = new INT[]{32, 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4};
Font crfont = null;
SizeF crsize = new SizeF ();
for (int i = 0;i < sizes. Length; i++)
{
Crfont = new Font ("Arial black", sizes[i], fontstyle.bold);
Crsize = picture. MeasureString (_watermarktext, Crfont);

if ((ushort) Crsize.width < (ushort) _width)
{
Break
}
}

Generate a watermark picture (write text to a picture)
Bitmap floatbmp = new Bitmap (int) Crsize.width + 3,
(int) Crsize.height + 3, PIXELFORMAT.FORMAT32BPPARGB);
Graphics fg=graphics.fromimage (floatbmp);
PointF pt=new PointF (0,0);

Draw Shadow Text
Brush TransparentBrush0 = new SolidBrush (Color.FromArgb (255, color.black));
Brush TransparentBrush1 = new SolidBrush (Color.FromArgb (255, color.black));
Fg. DrawString (_watermarktext,crfont,transparentbrush0, Pt. X, Pt. Y + 1);
Fg. DrawString (_watermarktext,crfont,transparentbrush0, Pt. X + 1, Pt. Y);

Fg. DrawString (_watermarktext,crfont,transparentbrush1, Pt. X + 1, Pt. Y + 1);
Fg. DrawString (_watermarktext,crfont,transparentbrush1, Pt. X, Pt. Y + 2);
Fg. DrawString (_watermarktext,crfont,transparentbrush1, Pt. X + 2, Pt. Y);

Transparentbrush0.dispose ();
Transparentbrush1.dispose ();

Draw text
Fg. smoothingmode=system.drawing.drawing2d.smoothingmode.highquality;
Fg. DrawString (_watermarktext,
Crfont, New SolidBrush (Color.White),
Pt. X, Pt. Y, Stringformat.genericdefault);

Save the action you just made
Fg. Save ();
Fg. Dispose ();
Floatbmp.save ("d:\\website\\digitalkm\\ttt.jpg");

Add a watermark image to the original artwork
This.addwatermarkimage (
Picture
New Bitmap (Floatbmp),
"Wm_bottom_right",
_width,
_height);
}

<summary>
Add watermark Picture
</summary>
<param name= "Picture" >imge object </param>
<param name= "Itheimage" >image object (watermark in this picture) </param>
<param name= "_watermarkposition" > Watermark location </param>
<param name= "_width" > Added watermark picture width </param>
<param name= "_height" > Added watermark Picture High </param>
private void Addwatermarkimage (Graphics picture,image itheimage,
String _watermarkposition,int _width,int _height)
{
Image watermark = new Bitmap (itheimage);

ImageAttributes imageattributes = new ImageAttributes ();
ColorMap ColorMap = new ColorMap ();

Colormap.oldcolor = Color.FromArgb (255, 0, 255, 0);
Colormap.newcolor = Color.FromArgb (0, 0, 0, 0);
Colormap[] remaptable = {ColorMap};

Imageattributes.setremaptable (remaptable, Coloradjusttype.bitmap);

Float[][] Colormatrixelements = {
New float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
New float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
New float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
New float[] {0.0f, 0.0f, 0.0f, 0.3f, 0.0f},
New float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
};

ColorMatrix ColorMatrix = new ColorMatrix (colormatrixelements);

Imageattributes.setcolormatrix (ColorMatrix, Colormatrixflag.default, Coloradjusttype.bitmap);

int xpos = 0;
int ypos = 0;
int watermarkwidth = 0;
int watermarkheight = 0;
Double bl = 1d;

Calculate the ratio of a watermark picture
Compare the 1/4 width of the background
if (_width > Watermark. Width * 4) && (_height > Watermark. Height * 4))
{
BL = 1;
}
else if (_width > Watermark. Width * 4) && (_height<watermark. Height * 4))
{
BL = convert.todouble (_HEIGHT/4)/convert.todouble (watermark. Height);

}
else if (_width < watermark. Width * 4) && (_height > Watermark. Height * 4))
{
BL = convert.todouble (_WIDTH/4)/convert.todouble (watermark. Width);
}
Else
{
if (_width * watermark. Height) > (_height * watermark. Width))
{
BL = convert.todouble (_HEIGHT/4)/convert.todouble (watermark. Height);

}
Else
{
BL = convert.todouble (_WIDTH/4)/convert.todouble (watermark. Width);

}

}

Watermarkwidth = Convert.ToInt32 (watermark. Width * BL);
Watermarkheight = Convert.ToInt32 (watermark. Height * BL);

Switch (_watermarkposition)
{
Case "Wm_top_left":
Xpos = 10;
Ypos = 10;
Break
Case "Wm_top_right":
Xpos = _width-watermarkwidth-10;
Ypos = 10;
Break
Case "Wm_bottom_right":
Xpos = _width-watermarkwidth-10;
Ypos = _height-watermarkheight-10;
Break
Case "Wm_bottom_left":
Xpos = 10;
Ypos = _height-watermarkheight-10;
Break
}

Picture. DrawImage (
Watermark,
New Rectangle (xpos, Ypos, Watermarkwidth, Watermarkheight),
0,
0,
Watermark. Width,
Watermark. Height,
GraphicsUnit.Pixel,
ImageAttributes);

Watermark. Dispose ();
Imageattributes.dispose ();
}

<summary>
Add watermark Picture
</summary>
<param name= "Picture" >imge object </param>
<param name= "Watermarkpicpath" > Watermark image Address </param>
<param name= "_watermarkposition" > Watermark location </param>
<param name= "_width" > Added watermark picture width </param>
<param name= "_height" > Added watermark Picture High </param>
private void Addwatermarkimage (Graphics picture,string Watermarkpicpath,
String _watermarkposition,int _width,int _height)
{
Image watermark = new Bitmap (Watermarkpicpath);

This.addwatermarkimage (picture, Watermark, _watermarkposition, _width,
_height);
}
#endregion

#region Generate thumbnails
<summary>
Save picture
</summary>
<param name= "image" >image object </param>
<param name= "Savepath" > Save path </param>
<param name= "ICI" > specified format for codec parameters </param>
private void SaveImage (image image, String savepath, ImageCodecInfo ici)
{
Set the EncoderParameters object for the original picture object
EncoderParameters parameters = new EncoderParameters (1);
Parameters. Param[0] = new Encoderparameter (
System.Drawing.Imaging.Encoder.Quality, ((Long) 90));
Image. Save (Savepath, ICI, parameters);
Parameters. Dispose ();
}

<summary>
Get all the relevant information about the image codec
</summary>
<param name= "MimeType" > A Multipurpose Internet Mail Extension Protocol (MIME) type containing codecs </param>
<returns> return all relevant information about the image codec </returns>
Private ImageCodecInfo Getcodecinfo (string mimetype)
{
imagecodecinfo[] Codecinfo = Imagecodecinfo.getimageencoders ();
foreach (ImageCodecInfo ici in codecinfo)
{
if (ICI. MimeType = = mimetype)
return ICI;
}
return null;
}

<summary>
Generate thumbnails
</summary>
<param name= "Sourceimagepath" > Original image Path (relative path) </param>
<param name= "Thumbnailimagepath" > The resulting thumbnail path, if empty, save as the original picture path (relative path) </param>
<param name= "Thumbnailimagewidth" > Thumbnail width (height is automatically generated by the proportion of the source picture) </param>
public void Tothumbnailimages (
String Sourceimagepath,
String Thumbnailimagepath,
int thumbnailimagewidth)
{
Hashtable htmimes = new Hashtable ();
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";

Get the suffix of the original picture
String sExt = Sourceimagepath.substring (
Sourceimagepath.lastindexof (".")). ToLower ();

Create an Image object from the original picture
Image image = Image.FromFile (Sourceimagepath);
int num = ((THUMBNAILIMAGEWIDTH/4) * 3);
int width = image. Width;
int height = image. Height;

Calculate the proportions of a picture
if (((double)/((double) height) >= 1.3333333333333333f)
{
num = ((height * thumbnailimagewidth)/width);
}
Else
{
Thumbnailimagewidth = ((width * num)/height);
}
if ((Thumbnailimagewidth < 1) | | (num < 1))
{
Return
}

Initializes a new instance of the Bitmap class with the specified size and format
Bitmap Bitmap = new Bitmap (thumbnailimagewidth, NUM,
PIXELFORMAT.FORMAT32BPPARGB);

Creates a new Graphics object from the specified Image object
Graphics Graphics = graphics.fromimage (bitmap);

Clear the entire drawing surface and fill with a transparent background color
Graphics. Clear (color.transparent);

Graphics. SmoothingMode = smoothingmode.highquality;
Graphics. Interpolationmode = Interpolationmode.high;

Draws the original picture object at the specified location and at the specified size
Graphics. DrawImage (Image, new Rectangle (0, 0, thumbnailimagewidth, num));
Image. Dispose ();

Try
{
Saves the original picture in the specified format and with the specified codec parameter to the specified file
SaveImage (Bitmap, Thumbnailimagepath,
Getcodecinfo ((String) htmimes[sext]);
}
catch (System.Exception e)
{
Throw e;
}
}
#endregion
}
}

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.