当前位置: 移动技术网 > IT编程>开发语言>c# > C#(.net)水印图片的生成完整实例

C#(.net)水印图片的生成完整实例

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文以一个完整实例讲述了c#水印图片的生成方法。是非常实用的技巧。分享给大家供大家参考。

具体实例代码如下:

/*
* 
*  使用说明:
*  建议先定义一个waterimage实例
*  然后利用实例的属性,去匹配需要进行操作的参数
*  然后定义一个waterimagemanage实例
*  利用waterimagemanage实例进行drawimage(),印图片水印
*  drawwords()印文字水印
* 
*/
using system;
using system.drawing;
using system.drawing.imaging;
using system.drawing.drawing2d;
using system.io;

namespace abc
{

  /// <summary>
  /// 图片位置
  /// </summary>
  public enum imageposition
  {
    lefttop,    //左上
    leftbottom,  //左下
    righttop,    //右上
    rigthbottom, //右下
    topmiddle,   //顶部居中
    bottommiddle, //底部居中
    center      //中心
  }

  /// <summary>
  /// 水印图片的操作管理 design by gary gong from demetersoft.com
  /// </summary>
  public class waterimagemanage
  {
    /// <summary>
    /// 生成一个新的水印图片制作实例
    /// </summary>
    public waterimagemanage()
    {
      //
      // todo: add constructor logic here
      //
    }

    /// <summary>
    /// 添加图片水印
    /// </summary>
    /// <param name="sourcepicture">源图片文件名</param>
    /// <param name="waterimage">水印图片文件名</param>
    /// <param name="alpha">透明度(0.1-1.0数值越小透明度越高)</param>
    /// <param name="position">位置</param>
    /// <param name="picturepath" >图片的路径</param>
    /// <returns>返回生成于指定文件夹下的水印文件名</returns>
    public string drawimage(string sourcepicture,
                     string waterimage,
                     float alpha,

                     imageposition position,
                     string picturepath)
    {
      //
      // 判断参数是否有效
      //
      if (sourcepicture == string.empty || waterimage == string.empty || alpha == 0.0 || picturepath == string.empty)
      {
        return sourcepicture;
      }

      //
      // 源图片,水印图片全路径
      //
      string sourcepicturename = picturepath + sourcepicture;
      string waterpicturename = picturepath + waterimage;
      string filesourceextension = system.io.path.getextension(sourcepicturename).tolower();
      string filewaterextension = system.io.path.getextension(waterpicturename).tolower();
      //
      // 判断文件是否存在,以及类型是否正确
      //
      if (system.io.file.exists(sourcepicturename) == false ||
        system.io.file.exists(waterpicturename) == false || (
        filesourceextension != ".gif" &&
        filesourceextension != ".jpg" &&
        filesourceextension != ".png") || (
        filewaterextension != ".gif" &&
        filewaterextension != ".jpg" &&
        filewaterextension != ".png")
        )
      {
        return sourcepicture;
      }

      //

      // 目标图片名称及全路径
      //
      string targetimage = sourcepicturename.replace(system.io.path.getextension(sourcepicturename), "") + "_1101.jpg";

      //
      // 将需要加上水印的图片装载到image对象中
      //
      image imgphoto = image.fromfile(sourcepicturename);
      //
      // 确定其长宽
      //
      int phwidth = imgphoto.width;
      int phheight = imgphoto.height;

      //
      // 封装 gdi+ 位图,此位图由图形图像及其属性的像素数据组成。
      //
      bitmap bmphoto = new bitmap(phwidth, phheight, pixelformat.format24bpprgb);

      //
      // 设定分辨率
      // 
      bmphoto.setresolution(imgphoto.horizontalresolution, imgphoto.verticalresolution);

      //
      // 定义一个绘图画面用来装载位图
      //
      graphics grphoto = graphics.fromimage(bmphoto);

      //
      //同样,由于水印是图片,我们也需要定义一个image来装载它
      //
      image imgwatermark = new bitmap(waterpicturename);

      //
      // 获取水印图片的高度和宽度
      //
      int wmwidth = imgwatermark.width;
      int wmheight = imgwatermark.height;

      //smoothingmode:指定是否将平滑处理(消除锯齿)应用于直线、曲线和已填充区域的边缘。
      // 成员名称  说明 
      // antialias   指定消除锯齿的呈现。 
      // default    指定不消除锯齿。

      // highquality 指定高质量、低速度呈现。 
      // highspeed  指定高速度、低质量呈现。 
      // invalid    指定一个无效模式。 
      // none     指定不消除锯齿。 
      grphoto.smoothingmode = smoothingmode.antialias;

 

      //
      // 第一次描绘,将我们的底图描绘在绘图画面上
      //
      grphoto.drawimage(imgphoto,
                    new rectangle(0, 0, phwidth, phheight),
                    0,
                    0,
                    phwidth,
                    phheight,
                    graphicsunit.pixel);

      //
      // 与底图一样,我们需要一个位图来装载水印图片。并设定其分辨率
      //
      bitmap bmwatermark = new bitmap(bmphoto);
      bmwatermark.setresolution(imgphoto.horizontalresolution, imgphoto.verticalresolution);

      //
      // 继续,将水印图片装载到一个绘图画面grwatermark
      //
      graphics grwatermark = graphics.fromimage(bmwatermark);

      //
      //imageattributes 对象包含有关在呈现时如何操作位图和图元文件颜色的信息。
      //   

      imageattributes imageattributes = new imageattributes();

      //
      //colormap: 定义转换颜色的映射
      //
      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}, // red红色
      new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, //green绿色
      new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, //blue蓝色    
      new float[] {0.0f, 0.0f, 0.0f, alpha, 0.0f}, //透明度   
      new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}};//

      // colormatrix:定义包含 rgba 空间坐标的 5 x 5 矩阵。
      // imageattributes 类的若干方法通过使用颜色矩阵调整图像颜色。
      colormatrix wmcolormatrix = new colormatrix(colormatrixelements);


      imageattributes.setcolormatrix(wmcolormatrix, colormatrixflag.default,
       coloradjusttype.bitmap);

      //
      //上面设置完颜色,下面开始设置位置
      //
      int xposofwm;
      int yposofwm;

      switch (position)
      {
        case imageposition.bottommiddle:
          xposofwm = (phwidth - wmwidth) / 2;
          yposofwm = phheight - wmheight - 10;
          break;

        case imageposition.center:
          xposofwm = (phwidth - wmwidth) / 2;
          yposofwm = (phheight - wmheight) / 2;
          break;
        case imageposition.leftbottom:
          xposofwm = 10;
          yposofwm = phheight - wmheight - 10;
          break;
        case imageposition.lefttop:
          xposofwm = 10;
          yposofwm = 10;
          break;
        case imageposition.righttop:
          xposofwm = phwidth - wmwidth - 10;
          yposofwm = 10;
          break;
        case imageposition.rigthbottom:
          xposofwm = phwidth - wmwidth - 10;
          yposofwm = phheight - wmheight - 10;
          break;
        case imageposition.topmiddle:
          xposofwm = (phwidth - wmwidth) / 2;
          yposofwm = 10;
          break;
        default:
          xposofwm = 10;
          yposofwm = phheight - wmheight - 10;
          break;
      }

      // 第二次绘图,把水印印上去
      //
      grwatermark.drawimage(imgwatermark,
       new rectangle(xposofwm,
                 yposofwm,
                 wmwidth,
                 wmheight),
                 0,
                 0,
                 wmwidth,
                 wmheight,
                 graphicsunit.pixel,
                 imageattributes);

      imgphoto = bmwatermark;
      grphoto.dispose();
      grwatermark.dispose();

      //
      // 保存文件到服务器的文件夹里面
      //
      imgphoto.save(targetimage, imageformat.jpeg);
      imgphoto.dispose();
      imgwatermark.dispose();
      return targetimage.replace(picturepath, "");
    }

/*
* 
* 使用说明:
*  建议先定义一个waterimage实例
*  然后利用实例的属性,去匹配需要进行操作的参数
*  然后定义一个waterimagemanage实例
*  利用waterimagemanage实例进行drawimage(),印图片水印
*  drawwords()印文字水印
* 
-*/

    /// <summary>
    /// 在图片上添加水印文字
    /// </summary>
    /// <param name="sourcepicture">源图片文件(文件名,不包括路径)</param>

    /// <param name="waterwords">需要添加到图片上的文字</param>
    /// <param name="alpha">透明度</param>
    /// <param name="position">位置</param>
    /// <param name="picturepath">文件路径</param>
    /// <returns></returns>
    public string drawwords(string sourcepicture,
                     string waterwords,
                     float alpha,
                     imageposition position,
                     string picturepath)
    {
      //
      // 判断参数是否有效
      //
      if (sourcepicture == string.empty || waterwords == string.empty || alpha == 0.0 || picturepath == string.empty)
      {
        return sourcepicture;
      }

      //
      // 源图片全路径
      //
      if (picturepath.substring(picturepath.length - 1, 1) != "/")
        picturepath += "/";
      string sourcepicturename = picturepath + sourcepicture;
      string fileextension = system.io.path.getextension(sourcepicturename).tolower();

      //
      // 判断文件是否存在,以及文件名是否正确
      //
      if (system.io.file.exists(sourcepicturename) == false || (
        fileextension != ".gif" &&
        fileextension != ".jpg" &&

        fileextension != ".png"))
      {
        return sourcepicture;
      }

      //
      // 目标图片名称及全路径
      //
      string targetimage = sourcepicturename.replace(system.io.path.getextension(sourcepicturename), "") + "_0703.jpg";

      //创建一个图片对象用来装载要被添加水印的图片
      image imgphoto = image.fromfile(sourcepicturename);

      //获取图片的宽和高
      int phwidth = imgphoto.width;
      int phheight = imgphoto.height;

      //
      //建立一个bitmap,和我们需要加水印的图片一样大小
      bitmap bmphoto = new bitmap(phwidth, phheight, pixelformat.format24bpprgb);

      //setresolution:设置此 bitmap 的分辨率
      //这里直接将我们需要添加水印的图片的分辨率赋给了bitmap
      bmphoto.setresolution(imgphoto.horizontalresolution, imgphoto.verticalresolution);

      //graphics:封装一个 gdi+ 绘图图面。
      graphics grphoto = graphics.fromimage(bmphoto);

      //设置图形的品质
      grphoto.smoothingmode = smoothingmode.antialias;

      //将我们要添加水印的图片按照原始大小描绘(复制)到图形中
      grphoto.drawimage(
       imgphoto,                      //  要添加水印的图片
       new rectangle(0, 0, phwidth, phheight), // 根据要添加的水印图片的宽和高
       0,                           // x方向从0点开始描绘
       0,                           // y方向

       phwidth,                      // x方向描绘长度
       phheight,                      // y方向描绘长度
       graphicsunit.pixel);               // 描绘的单位,这里用的是像素

      //根据图片的大小我们来确定添加上去的文字的大小
      //在这里我们定义一个数组来确定
      int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 };

      //字体
      font crfont = null;
      //矩形的宽度和高度,sizef有三个属性,分别为height高,width宽,isempty是否为空
      sizef crsize = new sizef();

      //利用一个循环语句来选择我们要添加文字的型号
      //直到它的长度比图片的宽度小
      for (int i = 0; i < 7; i++)
      {
        crfont = new font("arial", sizes[i], fontstyle.bold);

        //测量用指定的 font 对象绘制并用指定的 stringformat 对象格式化的指定字符串。
        crsize = grphoto.measurestring(waterwords, crfont);

        // ushort 关键字表示一种整数数据类型
        if ((ushort)crsize.width < (ushort)phwidth)
          break;
      }

      //截边5%的距离,定义文字显示(由于不同的图片显示的高和宽不同,所以按百分比截取)
      int ypixlesfrombottom = (int)(phheight * .05);

      //定义在图片上文字的位置
      float wmheight = crsize.height;
      float wmwidth = crsize.width;

      float xposofwm;

      float yposofwm;

   switch (position)
      {
        case imageposition.bottommiddle:
          xposofwm = phwidth / 2;
          yposofwm = phheight - wmheight - 10;
          break;
        case imageposition.center:
          xposofwm = phwidth / 2;
          yposofwm = phheight / 2;
          break;
        case imageposition.leftbottom:
          xposofwm = wmwidth;
          yposofwm = phheight - wmheight - 10;
          break;
        case imageposition.lefttop:
          xposofwm = wmwidth / 2;
          yposofwm = wmheight / 2;
          break;
        case imageposition.righttop:
          xposofwm = phwidth - wmwidth - 10;
          yposofwm = wmheight;
          break;
        case imageposition.rigthbottom:
          xposofwm = phwidth - wmwidth - 10;
          yposofwm = phheight - wmheight - 10;
          break;
        case imageposition.topmiddle:
          xposofwm = phwidth / 2;
          yposofwm = wmwidth;

          break;
        default:
          xposofwm = wmwidth;
          yposofwm = phheight - wmheight - 10;
          break;
      }

      //封装文本布局信息(如对齐、文字方向和 tab 停靠位),显示操作(如省略号插入和国家标准 (national) 数字替换)和 opentype 功能。
      stringformat strformat = new stringformat();

      //定义需要印的文字居中对齐
      strformat.alignment = stringalignment.center;

      //solidbrush:定义单色画笔。画笔用于填充图形形状,如矩形、椭圆、扇形、多边形和封闭路径。
      //这个画笔为描绘阴影的画笔,呈灰色
      int m_alpha = convert.toint32(256 * alpha);
      solidbrush semitransbrush2 = new solidbrush(color.fromargb(m_alpha, 0, 0, 0));

      //描绘文字信息,这个图层向右和向下偏移一个像素,表示阴影效果
      //drawstring 在指定矩形并且用指定的 brush 和 font 对象绘制指定的文本字符串。
      grphoto.drawstring(waterwords,                  //string of text
                    crfont,                     //font
                    semitransbrush2,              //brush
                    new pointf(xposofwm + 1, yposofwm + 1), //position
                    strformat);

      //从四个 argb 分量(alpha、红色、绿色和蓝色)值创建 color 结构,这里设置透明度为153
      //这个画笔为描绘正式文字的笔刷,呈白色
      solidbrush semitransbrush = new solidbrush(color.fromargb(153, 255, 255, 255));

      //第二次绘制这个图形,建立在第一次描绘的基础上
      grphoto.drawstring(waterwords,         //string of text
                    crfont,                  //font
                    semitransbrush,              //brush
                    new pointf(xposofwm, yposofwm), //position
                    strformat);

      //imgphoto是我们建立的用来装载最终图形的image对象
      //bmphoto是我们用来制作图形的容器,为bitmap对象
      imgphoto = bmphoto;
      //释放资源,将定义的graphics实例grphoto释放,grphoto功德圆满
      grphoto.dispose();

      //将grphoto保存
      imgphoto.save(targetimage, imageformat.jpeg);
      imgphoto.dispose();

      return targetimage.replace(picturepath, "");
    }
  }

  /// <summary>
  /// 装载水印图片的相关信息
  /// </summary>
  public class waterimage
  {
    public waterimage()
    {

    }

    private string m_sourcepicture;
    /// <summary>
    /// 源图片地址名字(带后缀)

    /// </summary>
    public string sourcepicture
    {
      get { return m_sourcepicture; }
      set { m_sourcepicture = value; }
    }

    private string m_waterimager;
    /// <summary>
    /// 水印图片名字(带后缀)
    /// </summary>
    public string waterpicture
    {
      get { return m_waterimager; }
      set { m_waterimager = value; }
    }

    private float m_alpha;
    /// <summary>
    /// 水印图片文字的透明度
    /// </summary>
    public float alpha
    {
      get { return m_alpha; }
      set { m_alpha = value; }
    }

    private imageposition m_postition;
    /// <summary>
    /// 水印图片或文字在图片中的位置
    /// </summary>
    public imageposition position
    {
      get { return m_postition; }
      set { m_postition = value; }
    }

    private string m_words;
    /// <summary>
    /// 水印文字的内容
    /// </summary>
    public string words
    {
      get { return m_words; }
      set { m_words = value; }
    }

  }
}

相信本文所述对大家的c#程序设计有一定的借鉴参考作用。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网