当前位置:  编程技术>.net/c#/asp.net

c#给图片添加文字的代码小结

    来源: 互联网  发布时间:2014-10-15

    本文导语:  代码实例一 代码如下: using System; using System.IO; using System.Collections; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; namespace Imag_writer { /// /// 水印的类型 /// public enum WaterMarkType {    ///    /// 文字水印    /...

代码实例一
代码如下:

using System;
using System.IO;
using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace Imag_writer
{
///
/// 水印的类型
///
public enum WaterMarkType
{
   ///
   /// 文字水印
   ///
   TextMark,
   ///
   /// 图片水印
   ///
   //ImageMark // 暂时只能添加文字水印
};
///
/// 水印的位置
///
public enum WaterMarkPosition
{
   ///
   /// 左上角
   ///
   WMP_Left_Top,
   ///
   /// 左下角
   ///
   WMP_Left_Bottom,
   ///
   /// 右上角
   ///
   WMP_Right_Top,
   ///
   /// 右下角
   ///
   WMP_Right_Bottom
};
///
/// 处理图片的类(包括加水印,生成缩略图)
///
public class ImageWaterMark
{
   public ImageWaterMark()
   {
    //
    // TODO: 在此处添加构造函数逻辑
    //
   }
   #region 给图片加水印
   ///
   /// 添加水印(分图片水印与文字水印两种)
   ///
   /// 原图片绝对地址
   /// 新图片放置的绝对地址
   /// 要添加的水印的类型
   /// 水印内容,若添加文字水印,此即为要添加的文字;
   /// 若要添加图片水印,此为图片的路径
   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);
     }
    }
   }
   ///
   ///   加水印文字
   ///
   /// imge 对象
   /// 水印文字内容
   /// 水印位置
   /// 被加水印图片的宽
   /// 被加水印图片的高
   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);
   }
   ///
   ///   加水印图片
   ///
   /// imge 对象
   /// Image对象(以此图片为水印)
   /// 水印位置
   /// 被加水印图片的宽
   /// 被加水印图片的高
   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(_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();
   }
   ///
   ///   加水印图片
   ///
   /// imge 对象
   /// 水印图片的地址
   /// 水印位置
   /// 被加水印图片的宽
   /// 被加水印图片的高
   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 生成缩略图
   ///
   /// 保存图片
   ///
   /// Image 对象
   /// 保存路径
   /// 指定格式的编解码参数
   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();
   }
   ///
   /// 获取图像编码解码器的所有相关信息
   ///
   /// 包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串
   /// 返回图像编码解码器的所有相关信息
   private ImageCodecInfo GetCodecInfo(string mimeType)
   {
    ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
    foreach(ImageCodecInfo ici in CodecInfo)
    {
     if(ici.MimeType == mimeType)
      return ici;
    }
    return null;
   }
   ///
   /// 生成缩略图
   ///
   /// 原图片路径(相对路径)
   /// 生成的缩略图路径,如果为空则保存为原图片路径(相对路径)
   /// 缩略图的宽度(高度与按源图片比例自动生成)
   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();
}
///
/// 从数据库中加载二进制图片
///
///
///
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;
}
///
/// 在原图片基础上加载文字水印
///
///
///
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;
}
///
/// 在原图片基础上加载图片水印
///
///
///
private void button3_Click(object sender, EventArgs e)
{
Graphics GImage = Graphics.FromImage(imgWeight);
addWatermarkImage(GImage, @"C:Documents and SettingsAdministrator桌面Mark.png", "WM_TOP_LEFT", imgWeight.Width, imgWeight.Height);
pictureBox1.Image = imgWeight;
}
///
/// 生成图片缩略图
///
///
///
private void button4_Click(object sender, EventArgs e)
{
GreateMiniImage(@"C:Documents and SettingsAdministrator桌面Source.jpg", @"C:Documents and SettingsAdministrator桌面Small.png", 100, 200);
}
///
/// 加水印文字
///
/// imge 对象
/// 水印文字内容
/// 水印位置
/// 被加水印图片的宽
/// 被加水印图片的高
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();
}
///
/// 加水印图片
///
/// imge 对象
/// 水印图片的地址
/// 水印位置
/// 被加水印图片的宽
/// 被加水印图片的高
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();
}
///
/// 生成缩略图
///
/// 原图片地址
/// 新图片地址
/// 缩略图的宽
/// 缩略图的高
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 = 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.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
{
}
}
}
}

    
 
 

您可能感兴趣的文章:

  • c#正则过滤图片标签 asp.net正则过滤的例子
  • C# 图片与二进制转换的简单实例
  • C#实现动态显示及动态移除图片方法
  • C#给picturebox控件加图片选中状态的2个方法
  • 基于C# winform实现图片上传功能的方法
  • C#实现图片放大功能的按照像素放大图像方法
  • C#实现把彩色图片灰度化代码分享
  • c#读取图像保存到数据库(数据库保存图片)实例
  • C#判断上传文件是否是图片以防止木马上传的方法
  • C#实现将网页保存成图片的网页拍照功能
  • c#实现图片与字节流相互转换的代码
  • C# 将字节流转换为图片的实例方法
  • c#图片处理之图片裁剪成不规则图形
  • c# Base64编码和图片的互相转换代码
  • C#保存图片到数据库并读取显示图片的方法
  • c#读取图像保存到数据库中(数据库保存图片)
  • C# 将透明图片的非透明区域转换成Region的实例代码
  • C#操作图片读取和存储SQLserver实现代码
  • C# 判断两张图片是否一致的快速方法
  • C#中按指定质量保存图片的实例代码
  •  
    本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
    本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • 请问如何向JTextPane中添加图片?解决必给分!!!
  • java中添加图片的问题
  • asp.net在图片上添加水印效果的代码示例
  • linux下采用shell脚本实现批量为指定文件夹下图片添加水印的方法
  • jquery实现添加图片淡入淡出效果的代码
  • 请问怎样向一指定图片文件(jpg,gif)的指定位置添加几个文字?多谢多谢!!!
  • c#添加图片水印类的代码举例
  • php实现图片添加水印功能
  • 发布Applet不能添加图片,。。。。help
  • php为png/jpg/gif格式图片添加水印
  • c# 给button添加不规则的图片以及用pictureBox替代button响应点击事件的方法
  • 校内网css代码添加背景图片常用代码
  • c#图片添加水印的实例代码
  • java.imageIo给图片添加水印的实现代码
  • php图片添加水印示例
  • C# 添加图片水印的代码示例
  • winform壁纸工具为图片添加当前月的日历信息
  • 给图片在博客中添加滤镜效果
  • iphone cocos2d 精灵的动画效果(图片,纹理,帧)CCAnimation实现
  • JS点击图片改变图片图径并用正则表达式取图片名的代码
  • Python3通过request.urlopen实现Web网页图片下载
  • Android 图片浏览器 雪梦图片浏览器
  • android中知道图片name时获取图片的简单方法
  • css为图片设置背景图片
  • android图像绘制(六)获取本地图片或拍照图片等图片资源
  • 有没有可以从已知图片里过滤出,不规则图片的滤镜??
  • 怎么让客户端从服务器下载图片后,看不到图片的最后修改时间
  • 如何将一个彩色bmp图片转换成黑白图片,急用
  • 查询图片,图片文件存放在数据库中好,还是存放路径好,是否有更好的解决办法
  • 图片和jlabel的大小不相同,怎样让图片充满整个jlabel?
  • PHP正则匹配图片并给图片加链接详解


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3