c code summary for adding text to images
- 2020-05-09 19:04:30
- OfStack
Code instance 1
Code instance 2
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 watermarking
/// </summary>
TextMark,
/// <summary>
/// Image watermarking
/// </summary>
//ImageMark // Only text watermarks can be added temporarily
};
/// <summary>
/// Watermark location
/// </summary>
public enum WaterMarkPosition
{
/// <summary>
/// The upper left corner
/// </summary>
WMP_Left_Top,
/// <summary>
/// The lower left corner
/// </summary>
WMP_Left_Bottom,
/// <summary>
/// The top right corner
/// </summary>
WMP_Right_Top,
/// <summary>
/// The lower right corner
/// </summary>
WMP_Right_Bottom
};
/// <summary>
/// Image processing classes (including watermarking, thumbnail generation)
/// </summary>
public class ImageWaterMark
{
public ImageWaterMark()
{
//
// TODO: Add the constructor logic here
//
}
#region Watermark the image
/// <summary>
/// Add a watermark ( There are two kinds of image watermarking and text watermarking )
/// </summary>
/// <param name="oldpath"> Absolute address of original picture </param>
/// <param name="newpath"> The absolute address at which new images are placed </param>
/// <param name="wmtType"> The type of watermark to add </param>
/// <param name="sWaterMarkContent"> Watermark content, if the text watermark is added, this is the text to be added;
/// To add a image watermark, this is the path to the image </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 watermarking
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>
/// Watermarked text
/// </summary>
/// <param name="picture">imge object </param>
/// <param name="_watermarkText"> Watermark text content </param>
/// <param name="_watermarkPosition"> The watermark position </param>
/// <param name="_width"> The width of a watermarked image </param>
/// <param name="_height"> The height of the watermarked image </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 watermark image (write text to image)
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 the text
fg.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.HighQuality;
fg.DrawString(_watermarkText,
crFont, new SolidBrush(Color.White),
pt.X, pt.Y, StringFormat.GenericDefault);
// Save the operation
fg.Save();
fg.Dispose();
// floatBmp.Save("d:\\WebSite\\DIGITALKM\\ttt.jpg");
// Add the watermark image to the original image
this.addWatermarkImage(
picture,
new Bitmap(floatBmp),
"WM_BOTTOM_RIGHT",
_width,
_height);
}
/// <summary>
/// Watermarked picture
/// </summary>
/// <param name="picture">imge object </param>
/// <param name="iTheImage">Image Object (this image is a watermark) </param>
/// <param name="_watermarkPosition"> The watermark position </param>
/// <param name="_width"> The width of a watermarked image </param>
/// <param name="_height"> The height of the watermarked image </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 watermark images
// Taking the background of the 1/4 Width to compare
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>
/// Watermarked picture
/// </summary>
/// <param name="picture">imge object </param>
/// <param name="WaterMarkPicPath"> The address of the watermark image </param>
/// <param name="_watermarkPosition"> The watermark position </param>
/// <param name="_width"> The width of a watermarked image </param>
/// <param name="_height"> The height of the watermarked image </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 the picture
/// </summary>
/// <param name="image">Image object </param>
/// <param name="savePath"> Save the path </param>
/// <param name="ici"> Specifies the encoding and decoding parameters for the format </param>
private void SaveImage(Image image, string savePath, ImageCodecInfo ici)
{
// Set up the The original image The object's EncoderParameters 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>
/// Gets all relevant information about the image codec
/// </summary>
/// <param name="mimeType"> Multipurpose Internet mail extension protocol containing codecs (MIME) Type string </param>
/// <returns> Returns 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 paths )</param>
/// <param name="thumbnailImagePath"> The generated thumbnail path , If it is empty, save it to the original image path ( Relative paths )</param>
/// <param name="thumbnailImageWidth"> Width of thumbnail (height is automatically generated in proportion to the source image) </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";
// Gets the suffix of the original image
string sExt = SourceImagePath.Substring(
SourceImagePath.LastIndexOf(".")).ToLower();
// from Original image creation Image object
Image image = Image.FromFile(SourceImagePath);
int num = ((ThumbnailImageWidth / 4) * 3);
int width = image.Width;
int height = image.Height;
// Calculate the proportion of the picture
if ((((double) width) / ((double) height)) >= 1.3333333333333333f)
{
num = ((height * ThumbnailImageWidth) / width);
}
else
{
ThumbnailImageWidth = ((width * num) / height);
}
if ((ThumbnailImageWidth < 1) || (num < 1))
{
return;
}
// Class with the specified size and format Bitmap class
Bitmap bitmap = new Bitmap(ThumbnailImageWidth, num,
PixelFormat.Format32bppArgb);
// From the specified Image Object creation new Graphics 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 at the specified location and at the specified size The original image object
graphics.DrawImage(image, new Rectangle(0, 0, ThumbnailImageWidth, num));
image.Dispose();
try
{
// Will this The original image Saves to the specified file in the specified format and with the specified encoding and decoding parameters
SaveImage(bitmap, ThumbnailImagePath,
GetCodecInfo((string)htmimes[sExt]));
}
catch(System.Exception e)
{
throw e;
}
}
#endregion
}
}
Code instance 2
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Drawing.Imaging;
/* Author : IT
* Date: 2011-11-13 14:52:53
* Blog: www.chenpan.name
*/
namespace WaterImage
{
public partial class Form2 : Form
{
Image imgWeight;
public Form2()
{
InitializeComponent();
}
/// <summary>
/// Load from the database 2 A binary image
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
string strSql = "Select Top 1 FileContent From Sys_FileSave";
Byte[] byteImage = new Byte[0];
byteImage = (Byte[])(DbHelperSQL.GetSingle(strSql));
MemoryStream stmBLOBData = new MemoryStream(byteImage);
imgWeight = Image.FromStream(stmBLOBData); pictureBox1.Image = imgWeight;
}
/// <summary>
/// The text watermark is loaded on the basis of the original image
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
Graphics GImage = Graphics.FromImage(imgWeight);
addWatermarkText(GImage, " Weight for 60.00 Tons of ", "WM_BOTTOM_RIGHT", imgWeight.Width, imgWeight.Height);
pictureBox1.Image = imgWeight;
}
/// <summary>
/// The image watermark is loaded on the basis of the original image
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
Graphics GImage = Graphics.FromImage(imgWeight);
addWatermarkImage(GImage, @"C:\Documents and Settings\Administrator\ desktop \Mark.png", "WM_TOP_LEFT", imgWeight.Width, imgWeight.Height);
pictureBox1.Image = imgWeight;
}
/// <summary>
/// Generate image thumbnails
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
GreateMiniImage(@"C:\Documents and Settings\Administrator\ desktop \Source.jpg", @"C:\Documents and Settings\Administrator\ desktop \Small.png", 100, 200);
}
/// <summary>
/// Watermarked text
/// </summary>
/// <param name="picture">imge object </param>
/// <param name="_watermarkText"> Watermark text content </param>
/// <param name="_watermarkPosition"> The watermark position </param>
/// <param name="_width"> The width of a watermarked image </param>
/// <param name="_height"> The height of the watermarked image </param>
private void addWatermarkText(Graphics picture, string _watermarkText, string _watermarkPosition, int _width, int _height)
{
int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 };
Font crFont = null;
SizeF crSize = new SizeF();
for (int i = 0; i < 7; i++)
{
crFont = new Font("arial", sizes[i], FontStyle.Bold);
crSize = picture.MeasureString(_watermarkText, crFont);
if ((ushort)crSize.Width < (ushort)_width)
break;
}
float xpos = 0;
float ypos = 0;
switch (_watermarkPosition)
{
case "WM_TOP_LEFT":
xpos = ((float)_width * (float).01) + (crSize.Width / 2);
ypos = (float)_height * (float).01;
break;
case "WM_TOP_RIGHT":
xpos = ((float)_width * (float).99) - (crSize.Width / 2);
ypos = (float)_height * (float).01;
break;
case "WM_BOTTOM_RIGHT":
xpos = ((float)_width * (float).99) - (crSize.Width / 2);
ypos = ((float)_height * (float).99) - crSize.Height;
break;
case "WM_BOTTOM_LEFT":
xpos = ((float)_width * (float).01) + (crSize.Width / 2);
ypos = ((float)_height * (float).99) - crSize.Height;
break;
}
StringFormat StrFormat = new StringFormat();
StrFormat.Alignment = StringAlignment.Center;
SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(153, 0, 0, 0));
picture.DrawString(_watermarkText, crFont, semiTransBrush2, xpos + 1, ypos + 1, StrFormat);
SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));
picture.DrawString(_watermarkText, crFont, semiTransBrush, xpos, ypos, StrFormat);
semiTransBrush2.Dispose();
semiTransBrush.Dispose();
}
/// <summary>
/// Watermarked picture
/// </summary>
/// <param name="picture">imge object </param>
/// <param name="WaterMarkPicPath"> The address of the watermark image </param>
/// <param name="_watermarkPosition"> The watermark position </param>
/// <param name="_width"> The width of a watermarked image </param>
/// <param name="_height"> The height of the watermarked image </param>
private void addWatermarkImage(Graphics picture, string WaterMarkPicPath, string _watermarkPosition, int _width, int _height)
{
Image watermark = new Bitmap(WaterMarkPicPath);
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 watermark images
// Taking the background of the 1/4 Width to compare
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>
/// Generate thumbnails
/// </summary>
/// <param name="oldpath"> Original picture address </param>
/// <param name="newpath"> New picture address </param>
/// <param name="tWidth"> The width of the thumbnail </param>
/// <param name="tHeight"> Height of thumbnail </param>
private void GreateMiniImage(string oldpath, string newpath, int tWidth, int tHeight)
{
try
{
System.Drawing.Image image = System.Drawing.Image.FromFile(oldpath);
double bl = 1d;
if ((image.Width <= image.Height) && (tWidth >= tHeight))
{
bl = Convert.ToDouble(image.Height) / Convert.ToDouble(tHeight);
}
else if ((image.Width > image.Height) && (tWidth < tHeight))
{
bl = Convert.ToDouble(image.Width) / Convert.ToDouble(tWidth);
}
else
if ((image.Width <= image.Height) && (tWidth <= tHeight))
{
if (image.Height / tHeight >= image.Width / tWidth)
{
bl = Convert.ToDouble(image.Width) / Convert.ToDouble(tWidth);
}
else
{
bl = Convert.ToDouble(image.Height) / Convert.ToDouble(tHeight);
}
}
else
{
if (image.Height / tHeight >= image.Width / tWidth)
{
bl = Convert.ToDouble(image.Height) / Convert.ToDouble(tHeight);
}
else
{
bl = Convert.ToDouble(image.Width) / Convert.ToDouble(tWidth);
}
}
Bitmap b = new Bitmap(image, Convert.ToInt32(image.Width / bl), Convert.ToInt32(image.Height / bl));
b.Save(newpath);
b.Dispose();
image.Dispose();
}
catch
{
}
}
}
}