欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-06 11:18:34
代码实例一 复制代码 代码如下: using system; using system.io; using system.collections; using system...
代码实例一
复制代码 代码如下:

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
{
}
}
}
}

上一篇: 浅谈MySQL临时表与派生表

下一篇: