程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> c#給圖片添加文字的代碼小結

c#給圖片添加文字的代碼小結

編輯:C#基礎知識
代碼實例一
代碼如下:

using System;
using System.IO;
using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace Imag_writer
{
/// <summary>
/// 水印的類型
/// </summary>
public enum WaterMarkType
{
   /// <summary>
   /// 文字水印
   /// </summary>
   TextMark,
   /// <summary>
   /// 圖片水印
   /// </summary>
   //ImageMark // 暫時只能添加文字水印
};
/// <summary>
/// 水印的位置
/// </summary>
public enum WaterMarkPosition
{
   /// <summary>
   /// 左上角
   /// </summary>
   WMP_Left_Top,
   /// <summary>
   /// 左下角
   /// </summary>
   WMP_Left_Bottom,
   /// <summary>
   /// 右上角
   /// </summary>
   WMP_Right_Top,
   /// <summary>
   /// 右下角
   /// </summary>
   WMP_Right_Bottom
};
/// <summary>
/// 處理圖片的類(包括加水印,生成縮略圖)
/// </summary>
public class ImageWaterMark
{
   public ImageWaterMark()
   {
    //
    // TODO: 在此處添加構造函數邏輯
    //
   }
   #region 給圖片加水印
   /// <summary>
   /// 添加水印(分圖片水印與文字水印兩種)
   /// </summary>
   /// <param name="oldpath">原圖片絕對地址</param>
   /// <param name="newpath">新圖片放置的絕對地址</param>
   /// <param name="wmtType">要添加的水印的類型</param>
   /// <param name="sWaterMarkContent">水印內容,若添加文字水印,此即為要添加的文字;
   /// 若要添加圖片水印,此為圖片的路徑</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:
       //文字水印
       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>
   ///   加水印文字
   /// </summary>
   /// <param name="picture">imge 對象</param>
   /// <param name="_watermarkText">水印文字內容</param>
   /// <param name="_watermarkPosition">水印位置</param>
   /// <param name="_width">被加水印圖片的寬</param>
   /// <param name="_height">被加水印圖片的高</param>
   private void addWatermarkText(Graphics picture, string _watermarkText,
    string _watermarkPosition, int _width, int _height)
   {
    // 確定水印文字的字體大小
    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;
     }
    }
    // 生成水印圖片(將文字寫到圖片中)
    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);
    // 畫陰影文字
    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();
    // 畫文字
    fg.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.HighQuality;
    fg.DrawString(_watermarkText,
     crFont, new SolidBrush(Color.White),
     pt.X, pt.Y, StringFormat.GenericDefault);
    // 保存剛才的操作
    fg.Save();
    fg.Dispose();
    // floatBmp.Save("d:\\WebSite\\DIGITALKM\\ttt.jpg");
    // 將水印圖片加到原圖中
    this.addWatermarkImage(
     picture,
     new Bitmap(floatBmp),
     "WM_BOTTOM_RIGHT",
     _width,
     _height);
   }
   /// <summary>
   ///   加水印圖片
   /// </summary>
   /// <param name="picture">imge 對象</param>
   /// <param name="iTheImage">Image對象(以此圖片為水印)</param>
   /// <param name="_watermarkPosition">水印位置</param>
   /// <param name="_width">被加水印圖片的寬</param>
   /// <param name="_height">被加水印圖片的高</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;
    //計算水印圖片的比率
    //取背景的1/4寬度來比較
    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>
   ///   加水印圖片
   /// </summary>
   /// <param name="picture">imge 對象</param>
   /// <param name="WaterMarkPicPath">水印圖片的地址</param>
   /// <param name="_watermarkPosition">水印位置</param>
   /// <param name="_width">被加水印圖片的寬</param>
   /// <param name="_height">被加水印圖片的高</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 生成縮略圖
   /// <summary>
   /// 保存圖片
   /// </summary>
   /// <param name="image">Image 對象</param>
   /// <param name="savePath">保存路徑</param>
   /// <param name="ici">指定格式的編解碼參數</param>
   private void SaveImage(Image image, string savePath, ImageCodecInfo ici)
   {
    //設置 原圖片 對象的 EncoderParameters 對象
    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>
   /// 獲取圖像編碼解碼器的所有相關信息
   /// </summary>
   /// <param name="mimeType">包含編碼解碼器的多用途網際郵件擴充協議 (MIME) 類型的字符串</param>
   /// <returns>返回圖像編碼解碼器的所有相關信息</returns>
   private ImageCodecInfo GetCodecInfo(string mimeType)
   {
    ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
    foreach(ImageCodecInfo ici in CodecInfo)
    {
     if(ici.MimeType == mimeType)
      return ici;
    }
    return null;
   }
   /// <summary>
   /// 生成縮略圖
   /// </summary>
   /// <param name="sourceImagePath">原圖片路徑(相對路徑)</param>
   /// <param name="thumbnailImagePath">生成的縮略圖路徑,如果為空則保存為原圖片路徑(相對路徑)</param>
   /// <param name="thumbnailImageWidth">縮略圖的寬度(高度與按源圖片比例自動生成)</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";
    // 取得原圖片的後綴
    string sExt = SourceImagePath.Substring(
     SourceImagePath.LastIndexOf(".")).ToLower();
    //從 原圖片創建 Image 對象
    Image image = Image.FromFile(SourceImagePath);
    int num = ((ThumbnailImageWidth / 4) * 3);
    int width = image.Width;
    int height = image.Height;
    //計算圖片的比例
    if ((((double) width) / ((double) height)) >= 1.3333333333333333f)
    {
     num = ((height * ThumbnailImageWidth) / width);
    }
    else
    {
     ThumbnailImageWidth = ((width * num) / height);
    }
    if ((ThumbnailImageWidth < 1) || (num < 1))
    {
     return;
    }
    //用指定的大小和格式初始化 Bitmap 類的新實例
    Bitmap bitmap = new Bitmap(ThumbnailImageWidth, num,
     PixelFormat.Format32bppArgb);
    //從指定的 Image 對象創建新 Graphics 對象
    Graphics graphics = Graphics.FromImage(bitmap);
    //清除整個繪圖面並以透明背景色填充
    graphics.Clear(Color.Transparent);
    graphics.SmoothingMode = SmoothingMode.HighQuality;
    graphics.InterpolationMode = InterpolationMode.High;
    //在指定位置並且按指定大小繪制 原圖片 對象
    graphics.DrawImage(image, new Rectangle(0, 0, ThumbnailImageWidth, num));
    image.Dispose();
    try
    {
     //將此 原圖片 以指定格式並用指定的編解碼參數保存到指定文件
     SaveImage(bitmap, ThumbnailImagePath,
      GetCodecInfo((string)htmimes[sExt]));
    }
    catch(System.Exception e)
    {
     throw e;
    }
   }
   #endregion
}
}

代碼實例二
代碼如下:

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>
/// 從數據庫中加載二進制圖片
/// </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>
/// 在原圖片基礎上加載文字水印
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
Graphics GImage = Graphics.FromImage(imgWeight);
addWatermarkText(GImage, "重量為60.00噸", "WM_BOTTOM_RIGHT", imgWeight.Width, imgWeight.Height);
pictureBox1.Image = imgWeight;
}
/// <summary>
/// 在原圖片基礎上加載圖片水印
/// </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\桌面\Mark.png", "WM_TOP_LEFT", imgWeight.Width, imgWeight.Height);
pictureBox1.Image = imgWeight;
}
/// <summary>
/// 生成圖片縮略圖
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
GreateMiniImage(@"C:\Documents and Settings\Administrator\桌面\Source.jpg", @"C:\Documents and Settings\Administrator\桌面\Small.png", 100, 200);
}
/// <summary>
/// 加水印文字
/// </summary>
/// <param name="picture">imge 對象</param>
/// <param name="_watermarkText">水印文字內容</param>
/// <param name="_watermarkPosition">水印位置</param>
/// <param name="_width">被加水印圖片的寬</param>
/// <param name="_height">被加水印圖片的高</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>
/// 加水印圖片
/// </summary>
/// <param name="picture">imge 對象</param>
/// <param name="WaterMarkPicPath">水印圖片的地址</param>
/// <param name="_watermarkPosition">水印位置</param>
/// <param name="_width">被加水印圖片的寬</param>
/// <param name="_height">被加水印圖片的高</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;
//計算水印圖片的比率
//取背景的1/4寬度來比較
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>
/// 生成縮略圖
/// </summary>
/// <param name="oldpath">原圖片地址</param>
/// <param name="newpath">新圖片地址</param>
/// <param name="tWidth">縮略圖的寬</param>
/// <param name="tHeight">縮略圖的高</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
{
}
}
}
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved