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

ASP.NET简单好用功能齐全图片上传工具类(水印、缩略图、裁剪等)

程序员文章站 2024-02-21 08:10:40
使用方法: uploadimage ui = new uploadimage(); /***可选参数***/ ui.setwo...

使用方法:

uploadimage ui = new uploadimage();
 
     /***可选参数***/
 
     ui.setwordwater = "哈哈";//文字水印
     // ui.setpicwater = server.mappath("2.png");//图片水印(图片和文字都赋值图片有效)
     ui.setpositionwater = 4;//水印图片的位置 0居中、1左上角、2右上角、3左下角、4右下角
 
     ui.setsmallimgheight = "110,40,20";//设置缩略图可以多个
     ui.setsmallimgwidth = "100,40,20";
 
     //保存图片生成缩略图
     var reponsemessage = ui.filesaveas(request.files[0], server.mappath("~/file/temp"));
 
     //裁剪图片
     var reponsemessage2 = ui.filecutsaveas(request.files[0], server.mappath("~/file/temp2"), 400, 300, uploadimage.cutmode.cutno);
 
 
 
 
     /***返回信息***/
     var iserror = reponsemessage.iserror;//是否异常
     var webpath = reponsemessage.webpath;//web路径
     var filepath = reponsemessage.filepath;//物理路径
     var message = reponsemessage.message;//错误信息
     var directory = reponsemessage.directory;//目录
     var smallpath1 = reponsemessage.smallpath(0);//缩略图路径1
     var smallpath2 = reponsemessage.smallpath(1);//缩略图路径2
     var smallpath3 = reponsemessage.smallpath(2);//缩略图路径3

 效果:

ASP.NET简单好用功能齐全图片上传工具类(水印、缩略图、裁剪等)

 源码:

using system;
using system.collections.generic;
using system.text;
using system.io;
using system.web;
using system.drawing;
using system.drawing.imaging;
using system.drawing.drawing2d;
using system.collections;
using system.net;
using system.text.regularexpressions;
using system.configuration;
 
namespace syntacticsugar
{
  /// <summary>
  /// ** 描述:图片上传类、支持水印、缩略图
  /// ** 创始时间:2015-5-28
  /// ** 修改时间:-
  /// ** 修改人:sunkaixuan
  /// </summary>
  public class uploadimage
  {
 
    #region 属性
    /// <summary>
    /// 允许图片格式
    /// </summary>
    public string setallowformat { get; set; }
    /// <summary>
    /// 允许上传图片大小
    /// </summary>
    public double setallowsize { get; set; }
    /// <summary>
    /// 文字水印字符
    /// </summary>
    public string setwordwater { get; set; }
    /// <summary>
    /// 图片水印
    /// </summary>
    public string setpicwater { get; set; }
    /// <summary>
    /// 水印图片的位置 0居中、1左上角、2右上角、3左下角、4右下角
    /// </summary>
    public int setpositionwater { get; set; }
    /// <summary>
    /// 缩略图宽度多个逗号格开(例如:200,100)
    /// </summary>
    public string setsmallimgwidth { get; set; }
    /// <summary>
    /// 缩略图高度多个逗号格开(例如:200,100)
    /// </summary>
    public string setsmallimgheight { get; set; }
    /// <summary>
    /// 是否限制最大宽度,默认为true
    /// </summary>
    public bool setlimitwidth { get; set; }
    /// <summary>
    /// 最大宽度尺寸,默认为600
    /// </summary>
    public int setmaxwidth { get; set; }
    /// <summary>
    /// 是否剪裁图片,默认true
    /// </summary>
    public bool setcutimage { get; set; }
    /// <summary>
    /// 限制图片最小宽度,0表示不限制
    /// </summary>
    public int setminwidth { get; set; }
 
    #endregion
 
    public uploadimage()
    {
      setallowformat = ".jpeg|.jpg|.bmp|.gif|.png";  //允许图片格式
      setallowsize = 1;    //允许上传图片大小,默认为1mb
      setpositionwater = 4;
      setcutimage = true;
    }
 
 
 
    #region main method
 
 
    /// <summary>
    /// 裁剪图片
    /// </summary>
    /// <param name="postedfile">httppostedfile控件</param>
    /// <param name="savepath">保存路径【sys.config配置路径】</param>
    /// <param name="oimgwidth">图片宽度</param>
    /// <param name="oimgheight">图片高度</param>
    /// <param name="cmode">剪切类型</param>
    /// <param name="ext">返回格式</param>
    /// <returns>返回上传信息</returns>
    public responsemessage filecutsaveas(system.web.httppostedfile postedfile, string savepath, int oimgwidth, int oimgheight, cutmode cmode)
    {
      responsemessage rm = new responsemessage();
      try
      {
        //获取上传文件的扩展名
        string sex = system.io.path.getextension(postedfile.filename);
        if (!checkvalidext(setallowformat, sex))
        {
          tryerror(rm, 2);
          return rm;
        }
 
        //获取上传文件的大小
        double postfilesize = postedfile.contentlength / 1024.0 / 1024.0;
 
        if (postfilesize > setallowsize)
        {
          tryerror(rm, 3);
          return rm; //超过文件上传大小
        }
        if (!system.io.directory.exists(savepath))
        {
          system.io.directory.createdirectory(savepath);
        }
        //重命名名称
        string newfilename = datetime.now.year.tostring() + datetime.now.month.tostring() + datetime.now.day.tostring() + datetime.now.hour.tostring() + datetime.now.minute.tostring() + datetime.now.second.tostring() + datetime.now.millisecond.tostring("000");
        string fname = "s" + newfilename + sex;
        string fullpath = path.combine(savepath, fname);
        postedfile.saveas(fullpath);
 
        //重命名名称
        string snewfilename = datetime.now.year.tostring() + datetime.now.month.tostring() + datetime.now.day.tostring() + datetime.now.hour.tostring() + datetime.now.minute.tostring() + datetime.now.second.tostring() + datetime.now.millisecond.tostring("000");
        string sfname = snewfilename + sex;
        rm.iserror = false;
        rm.filename = sfname;
        string sfullpath = path.combine(savepath, sfname);
        rm.filepath = sfullpath;
        rm.webpath = "/"+sfullpath.replace(httpcontext.current.server.mappath("~/"), "").replace("\\", "/");
        createsmallphoto(fullpath, oimgwidth, oimgheight, sfullpath, setpicwater, setwordwater, cmode);
        if (file.exists(fullpath))
        {
          file.delete(fullpath);
        }
        //压缩
        if (postfilesize > 100)
        {
          compressphoto(sfullpath, 100);
        }
      }
      catch (exception ex)
      {
        tryerror(rm, ex.message);
      }
      return rm;
    }
 
 
 
    /// <summary>
    /// 通用图片上传类
    /// </summary>
    /// <param name="postedfile">httppostedfile控件</param>
    /// <param name="savepath">保存路径【sys.config配置路径】</param>
    /// <param name="finame">返回文件名</param>
    /// <param name="fisize">返回文件大小</param>
    /// <returns>返回上传信息</returns>
    public responsemessage filesaveas(system.web.httppostedfile postedfile, string savepath)
    {
      responsemessage rm = new responsemessage();
      try
      {
        if (string.isnullorempty(postedfile.filename))
        {
          tryerror(rm, 4);
          return rm;
        }
 
        random rd = new random();
        int rdint = rd.next(1000, 9999);
        //重命名名称
        string newfilename = datetime.now.year.tostring() + datetime.now.month.tostring() + datetime.now.day.tostring() + datetime.now.hour.tostring() + datetime.now.minute.tostring() + datetime.now.second.tostring() + datetime.now.millisecond.tostring() + rdint;
 
        //获取上传文件的扩展名
        string sex = system.io.path.getextension(postedfile.filename);
        if (!checkvalidext(setallowformat, sex))
        {
          tryerror(rm, 2);
          return rm;
        }
 
        //获取上传文件的大小
        double postfilesize = postedfile.contentlength / 1024.0 / 1024.0;
 
        if (postfilesize > setallowsize)
        {
          tryerror(rm, 3);
          return rm;
        }
 
 
        if (!system.io.directory.exists(savepath))
        {
          system.io.directory.createdirectory(savepath);
        }
 
        rm.filename = newfilename + sex;
        string fullpath = savepath.trim('\\') + "\\" + rm.filename;
        rm.webpath = "/"+fullpath.replace(httpcontext.current.server.mappath("~/"), "").replace("\\", "/");
        rm.filepath = fullpath;
        rm.size = postfilesize;
        postedfile.saveas(fullpath);
 
 
        system.drawing.bitmap bmp = new bitmap(fullpath);
        int realwidth = bmp.width;
        int realheight = bmp.height;
        bmp.dispose();
 
        #region 检测图片宽度限制
        if (setminwidth > 0)
        {
          if (realwidth < setminwidth)
          {
            tryerror(rm, 7);
            return rm;
          }
        }
        #endregion
 
        #region 监测图片宽度是否超过600,超过的话,自动压缩到600
        if (setlimitwidth && realwidth > setmaxwidth)
        {
          int mwidth = setmaxwidth;
          int mheight = mwidth * realheight / realwidth;
 
          string tempfile = savepath + guid.newguid().tostring() + sex;
          file.move(fullpath, tempfile);
          createsmallphoto(tempfile, mwidth, mheight, fullpath, "", "");
          file.delete(tempfile);
        }
        #endregion
 
        #region 压缩图片存储尺寸
        if (sex.tolower() != ".gif")
        {
          compressphoto(fullpath, 100);
        }
        #endregion
 
 
 
        //生成缩略图片高宽
        if (string.isnullorempty(setsmallimgwidth))
        {
          rm.message = "上传成功,无缩略图";
          return rm;
        }
 
 
        string[] owidtharray = setsmallimgwidth.split(',');
        string[] oheightarray = setsmallimgheight.split(',');
        if (owidtharray.length != oheightarray.length)
        {
          tryerror(rm, 6);
          return rm;
        }
 
 
        for (int i = 0; i < owidtharray.length; i++)
        {
          if (convert.toint32(owidtharray[i]) <= 0 || convert.toint32(oheightarray[i]) <= 0)
            continue;
 
          string simg = savepath.trimend('\\') + '\\' + newfilename + "_" + i.tostring() + sex;
 
          //判断图片高宽是否大于生成高宽。否则用原图
          if (realwidth > convert.toint32(owidtharray[i]))
          {
            if (setcutimage)
              createsmallphoto(fullpath, convert.toint32(owidtharray[i]), convert.toint32(oheightarray[i]), simg, "", "");
            else
              createsmallphoto(fullpath, convert.toint32(owidtharray[i]), convert.toint32(oheightarray[i]), simg, "", "", cutmode.cutno);
          }
          else
          {
            if (setcutimage)
              createsmallphoto(fullpath, realwidth, realheight, simg, "", "");
            else
              createsmallphoto(fullpath, realwidth, realheight, simg, "", "", cutmode.cutno);
          }
        }
 
        #region 给大图添加水印
        if (!string.isnullorempty(setpicwater))
          attachpng(setpicwater, fullpath);
        else if (!string.isnullorempty(setwordwater))
          attachtext(setwordwater, fullpath);
        #endregion
 
 
      }
      catch (exception ex)
      {
        tryerror(rm, ex.message);
      }
      return rm;
    }
 
    #region 验证格式
    /// <summary>
    /// 验证格式
    /// </summary>
    /// <param name="alltype">所有格式</param>
    /// <param name="chktype">被检查的格式</param>
    /// <returns>bool</returns>
    public bool checkvalidext(string alltype, string chktype)
    {
      bool flag = false;
      string[] sarray = alltype.split('|');
      foreach (string temp in sarray)
      {
        if (temp.tolower() == chktype.tolower())
        {
          flag = true;
          break;
        }
      }
 
      return flag;
    }
    #endregion
 
    #region 根据需要的图片尺寸,按比例剪裁原始图片
    /// <summary>
    /// 根据需要的图片尺寸,按比例剪裁原始图片
    /// </summary>
    /// <param name="nwidth">缩略图宽度</param>
    /// <param name="nheight">缩略图高度</param>
    /// <param name="img">原始图片</param>
    /// <returns>剪裁区域尺寸</returns>
    public size cutregion(int nwidth, int nheight, image img)
    {
      double width = 0.0;
      double height = 0.0;
 
      double nw = (double)nwidth;
      double nh = (double)nheight;
 
      double pw = (double)img.width;
      double ph = (double)img.height;
 
      if (nw / nh > pw / ph)
      {
        width = pw;
        height = pw * nh / nw;
      }
      else if (nw / nh < pw / ph)
      {
        width = ph * nw / nh;
        height = ph;
      }
      else
      {
        width = pw;
        height = ph;
      }
 
      return new size(convert.toint32(width), convert.toint32(height));
    }
    #endregion
 
    #region 等比例缩小图片
    public size newsize(int nwidth, int nheight, image img)
    {
      double w = 0.0;
      double h = 0.0;
      double sw = convert.todouble(img.width);
      double sh = convert.todouble(img.height);
      double mw = convert.todouble(nwidth);
      double mh = convert.todouble(nheight);
 
      if (sw < mw && sh < mh)
      {
        w = sw;
        h = sh;
      }
      else if ((sw / sh) > (mw / mh))
      {
        w = nwidth;
        h = (w * sh) / sw;
      }
      else
      {
        h = nheight;
        w = (h * sw) / sh;
      }
 
      return new size(convert.toint32(w), convert.toint32(h));
    }
    #endregion
 
    #region 生成缩略图
 
    #region 生成缩略图,不加水印
    /// <summary>
    /// 生成缩略图,不加水印
    /// </summary>
    /// <param name="filename">源文件</param>
    /// <param name="nwidth">缩略图宽度</param>
    /// <param name="nheight">缩略图高度</param>
    /// <param name="destfile">缩略图保存位置</param>
    public void createsmallphoto(string filename, int nwidth, int nheight, string destfile)
    {
      image img = image.fromfile(filename);
      imageformat thisformat = img.rawformat;
 
      size cutsize = cutregion(nwidth, nheight, img);
      bitmap outbmp = new bitmap(nwidth, nheight);
      graphics g = graphics.fromimage(outbmp);
 
      // 设置画布的描绘质量
      g.compositingquality = compositingquality.highquality;
      g.smoothingmode = smoothingmode.highquality;
      g.interpolationmode = interpolationmode.highqualitybicubic;
 
      int nstartx = (img.width - cutsize.width) / 2;
      int nstarty = (img.height - cutsize.height) / 2;
 
      g.drawimage(img, new rectangle(0, 0, nwidth, nheight),
        nstartx, nstarty, cutsize.width, cutsize.height, graphicsunit.pixel);
      g.dispose();
 
      //if (thisformat.equals(imageformat.gif))
      //{
      //  response.contenttype = "image/gif";
      //}
      //else
      //{
      //  response.contenttype = "image/jpeg";
      //}
 
      // 以下代码为保存图片时,设置压缩质量
      encoderparameters encoderparams = new encoderparameters();
      long[] quality = new long[1];
      quality[0] = 100;
 
      encoderparameter encoderparam = new encoderparameter(system.drawing.imaging.encoder.quality, quality);
      encoderparams.param[0] = encoderparam;
 
      //获得包含有关内置图像编码解码器的信息的imagecodecinfo 对象。
      imagecodecinfo[] arrayici = imagecodecinfo.getimageencoders();
      imagecodecinfo jpegici = null;
      for (int x = 0; x < arrayici.length; x++)
      {
        if (arrayici[x].formatdescription.equals("jpeg"))
        {
          jpegici = arrayici[x];//设置jpeg编码
          break;
        }
      }
 
      if (jpegici != null)
      {
        //outbmp.save(response.outputstream, jpegici, encoderparams);
        outbmp.save(destfile, jpegici, encoderparams);
      }
      else
      {
        //outbmp.save(response.outputstream, thisformat);
        outbmp.save(destfile, thisformat);
      }
 
      img.dispose();
      outbmp.dispose();
    }
    #endregion
 
    #region 生成缩略图,加水印
    public void createsmallphoto(string filename, int nwidth, int nheight, string destfile, string sy, int ntype)
    {
      if (ntype == 0)
        createsmallphoto(filename, nwidth, nheight, destfile, sy, "");
      else
        createsmallphoto(filename, nwidth, nheight, destfile, "", sy);
    }
    #endregion
 
    #region 生成缩略图
    /// <summary>
    /// 生成缩略图
    /// </summary>
    /// <param name="filename">源文件</param>
    /// <param name="nwidth">缩略图宽度</param>
    /// <param name="nheight">缩略图高度</param>
    /// <param name="destfile">缩略图保存位置</param>
    /// <param name="png">图片水印</param>
    /// <param name="text">文本水印</param>
    public void createsmallphoto(string filename, int nwidth, int nheight, string destfile, string png, string text)
    {
      image img = image.fromfile(filename);
      imageformat thisformat = img.rawformat;
 
      size cutsize = cutregion(nwidth, nheight, img);
      bitmap outbmp = new bitmap(nwidth, nheight);
      graphics g = graphics.fromimage(outbmp);
      g.clear(color.white);
 
      // 设置画布的描绘质量
      g.compositingquality = compositingquality.highquality;
      g.smoothingmode = smoothingmode.highquality;
      g.interpolationmode = interpolationmode.highqualitybicubic;
 
      int nstartx = (img.width - cutsize.width) / 2;
      int nstarty = (img.height - cutsize.height) / 2;
 
      g.drawimage(img, new rectangle(0, 0, nwidth, nheight),
        nstartx, nstarty, cutsize.width, cutsize.height, graphicsunit.pixel);
      g.dispose();
 
      // 以下代码为保存图片时,设置压缩质量
      encoderparameters encoderparams = new encoderparameters();
      long[] quality = new long[1];
      quality[0] = 100;
 
      encoderparameter encoderparam = new encoderparameter(system.drawing.imaging.encoder.quality, quality);
      encoderparams.param[0] = encoderparam;
 
      //获得包含有关内置图像编码解码器的信息的imagecodecinfo 对象。
      imagecodecinfo[] arrayici = imagecodecinfo.getimageencoders();
      imagecodecinfo jpegici = null;
      for (int x = 0; x < arrayici.length; x++)
      {
        if (arrayici[x].formatdescription.equals("jpeg"))
        {
          jpegici = arrayici[x];//设置jpeg编码
          break;
        }
      }
 
      if (jpegici != null)
      {
        outbmp.save(destfile, jpegici, encoderparams);
      }
      else
      {
        outbmp.save(destfile, thisformat);
      }
 
      img.dispose();
      outbmp.dispose();
 
      if (!string.isnullorempty(png))
        attachpng(png, destfile);
 
      if (!string.isnullorempty(text))
        attachtext(text, destfile);
    }
 
 
    public void createsmallphoto(string filename, int nwidth, int nheight, string destfile, string png, string text, cutmode cmode)
    {
      image img = image.fromfile(filename);
 
      if (nwidth <= 0)
        nwidth = img.width;
      if (nheight <= 0)
        nheight = img.height;
 
      int towidth = nwidth;
      int toheight = nheight;
 
      switch (cmode)
      {
        case cutmode.cutwh://指定高宽缩放(可能变形)       
          break;
        case cutmode.cutw://指定宽,高按比例         
          toheight = img.height * nwidth / img.width;
          break;
        case cutmode.cuth://指定高,宽按比例
          towidth = img.width * nheight / img.height;
          break;
        case cutmode.cutno: //缩放不剪裁
          int maxsize = (nwidth >= nheight ? nwidth : nheight);
          if (img.width >= img.height)
          {
            towidth = maxsize;
            toheight = img.height * maxsize / img.width;
          }
          else
          {
            toheight = maxsize;
            towidth = img.width * maxsize / img.height;
          }
          break;
        default:
          break;
      }
      nwidth = towidth;
      nheight = toheight;
 
      imageformat thisformat = img.rawformat;
 
      size cutsize = new size(nwidth, nheight);
      if (cmode != cutmode.cutno)
        cutsize = cutregion(nwidth, nheight, img);
 
      bitmap outbmp = new bitmap(cutsize.width, cutsize.height);
 
      graphics g = graphics.fromimage(outbmp);
      g.clear(color.white);
 
      // 设置画布的描绘质量
      g.compositingquality = compositingquality.highquality;
      g.smoothingmode = smoothingmode.highquality;
      g.interpolationmode = interpolationmode.highqualitybicubic;
 
      int nstartx = (img.width - cutsize.width) / 2;
      int nstarty = (img.height - cutsize.height) / 2;
 
      //int x1 = (outbmp.width - nwidth) / 2;
      //int y1 = (outbmp.height - nheight) / 2;
 
      if (cmode != cutmode.cutno)
        g.drawimage(img, new rectangle(0, 0, nwidth, nheight),
          nstartx, nstarty, cutsize.width, cutsize.height, graphicsunit.pixel);
      else
        g.drawimage(img, new rectangle(0, 0, nwidth, nheight),
        0, 0, img.width, img.height, graphicsunit.pixel);
      g.dispose();
 
      // 以下代码为保存图片时,设置压缩质量
      encoderparameters encoderparams = new encoderparameters();
      long[] quality = new long[1];
      quality[0] = 100;
 
      encoderparameter encoderparam = new encoderparameter(system.drawing.imaging.encoder.quality, quality);
      encoderparams.param[0] = encoderparam;
 
      //获得包含有关内置图像编码解码器的信息的imagecodecinfo 对象。
      imagecodecinfo[] arrayici = imagecodecinfo.getimageencoders();
      imagecodecinfo jpegici = null;
      for (int x = 0; x < arrayici.length; x++)
      {
        if (arrayici[x].formatdescription.equals("jpeg"))
        {
          jpegici = arrayici[x];//设置jpeg编码
          break;
        }
      }
 
      if (jpegici != null)
      {
        outbmp.save(destfile, jpegici, encoderparams);
      }
      else
      {
        outbmp.save(destfile, thisformat);
      }
 
      img.dispose();
      outbmp.dispose();
 
      if (!string.isnullorempty(png))
        attachpng(png, destfile);
 
      if (!string.isnullorempty(text))
        attachtext(text, destfile);
    }
    #endregion
 
    #endregion
 
    #region 添加文字水印
    public void attachtext(string text, string file)
    {
      if (string.isnullorempty(text))
        return;
 
      if (!system.io.file.exists(file))
        return;
 
      system.io.fileinfo ofile = new system.io.fileinfo(file);
      string strtempfile = system.io.path.combine(ofile.directoryname, guid.newguid().tostring() + ofile.extension);
      ofile.copyto(strtempfile);
 
      image img = image.fromfile(strtempfile);
      imageformat thisformat = img.rawformat;
 
      int nheight = img.height;
      int nwidth = img.width;
 
      bitmap outbmp = new bitmap(nwidth, nheight);
      graphics g = graphics.fromimage(outbmp);
      g.clear(color.white);
 
      // 设置画布的描绘质量
      g.compositingquality = compositingquality.highquality;
      g.smoothingmode = smoothingmode.highquality;
      g.interpolationmode = interpolationmode.highqualitybicubic;
 
      g.drawimage(img, new rectangle(0, 0, nwidth, nheight),
        0, 0, nwidth, nheight, graphicsunit.pixel);
 
      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++)
      {
        //设置字体,这里是用arial,黑体
        crfont = new font("arial", sizes[i], fontstyle.bold);
        //measure the copyright string in this font
        crsize = g.measurestring(text, crfont);
 
        if ((ushort)crsize.width < (ushort)nwidth)
          break;
      }
 
      //因为图片的高度可能不尽相同, 所以定义了
      //从图片底部算起预留了5%的空间
      int ypixlesfrombottom = (int)(nheight * .08);
 
      //现在使用版权信息字符串的高度来确定要绘制的图像的字符串的y坐标
 
      float yposfrombottom = ((nheight - ypixlesfrombottom) - (crsize.height / 2));
 
      //计算x坐标
      float xcenterofimg = (nwidth / 2);
 
      //把文本布局设置为居中
      stringformat strformat = new stringformat();
      strformat.alignment = stringalignment.center;
 
      //通过brush来设置黑色半透明
      solidbrush semitransbrush2 = new solidbrush(color.fromargb(153, 0, 0, 0));
 
      //绘制版权字符串
      g.drawstring(text,         //版权字符串文本
        crfont,                  //字体
        semitransbrush2,              //brush
        new pointf(xcenterofimg + 1, yposfrombottom + 1), //位置
        strformat);
 
      //设置成白色半透明
      solidbrush semitransbrush = new solidbrush(color.fromargb(153, 255, 255, 255));
 
      //第二次绘制版权字符串来创建阴影效果
      //记住移动文本的位置1像素
      g.drawstring(text,         //版权文本
        crfont,                  //字体
        semitransbrush,              //brush
        new pointf(xcenterofimg, yposfrombottom), //位置
        strformat);
 
      g.dispose();
 
      // 以下代码为保存图片时,设置压缩质量
      encoderparameters encoderparams = new encoderparameters();
      long[] quality = new long[1];
      quality[0] = 100;
 
      encoderparameter encoderparam = new encoderparameter(system.drawing.imaging.encoder.quality, quality);
      encoderparams.param[0] = encoderparam;
 
      //获得包含有关内置图像编码解码器的信息的imagecodecinfo 对象。
      imagecodecinfo[] arrayici = imagecodecinfo.getimageencoders();
      imagecodecinfo jpegici = null;
      for (int x = 0; x < arrayici.length; x++)
      {
        if (arrayici[x].formatdescription.equals("jpeg"))
        {
          jpegici = arrayici[x];//设置jpeg编码
          break;
        }
      }
 
      if (jpegici != null)
      {
        outbmp.save(file, jpegici, encoderparams);
      }
      else
      {
        outbmp.save(file, thisformat);
      }
 
      img.dispose();
      outbmp.dispose();
 
      system.io.file.delete(strtempfile);
    }
    #endregion
 
    #region 添加图片水印
    ///<summary>
    /// 添加图片水印
    /// </summary>
    /// <param name="png">水印图片</param>
    /// <param name="file">原文件</param>
    /// <param name="position">水印图片的位置 0居中、1左上角、2右上角、3左下角、4右下角</param>
    public void attachpng(string png, string file)
    {
      if (string.isnullorempty(png))
        return;
 
      if (!system.io.file.exists(png))
        return;
 
      if (!system.io.file.exists(file))
        return;
 
      system.io.fileinfo ofile = new system.io.fileinfo(file);
      string strtempfile = system.io.path.combine(ofile.directoryname, guid.newguid().tostring() + ofile.extension);
      ofile.copyto(strtempfile);
 
      image img = image.fromfile(strtempfile);
      imageformat thisformat = img.rawformat;
      int nheight = img.height;
      int nwidth = img.width;
 
      bitmap outbmp = new bitmap(nwidth, nheight);
      graphics g = graphics.fromimage(outbmp);
 
      // 设置画布的描绘质量
      g.compositingquality = compositingquality.highquality;
      g.smoothingmode = smoothingmode.highquality;
      g.interpolationmode = interpolationmode.highqualitybicubic;
 
      g.drawimage(img, new rectangle(0, 0, nwidth, nheight),
        0, 0, nwidth, nheight, graphicsunit.pixel);
 
      img.dispose();
 
      img = image.fromfile(png);
 
      //bitmap bmppng = new bitmap(img);
 
      //imageattributes imageattr = new imageattributes();
      //color bg = color.green;
      //imageattr.setcolorkey(bg, bg);
 
      size pngsize = newsize(nwidth, nheight, img);
      int nx = 0;
      int ny = 0;
      int padding = 10;
      if (setpositionwater == 0)
      {
        nx = (nwidth - pngsize.width) / 2;
        ny = (nheight - pngsize.height) / 2;
      }
      else if (setpositionwater == 1)
      {
        nx = padding;
        ny = padding;
      }
      else if (setpositionwater == 2)
      {
        nx = (nwidth - pngsize.width) - padding;
        ny = padding;
      }
      else if (setpositionwater == 3)
      {
        nx = padding;
        ny = (nheight - pngsize.height) - padding;
      }
      else
      {
        nx = (nwidth - pngsize.width) - padding;
        ny = (nheight - pngsize.height) - padding;
      }
      g.drawimage(img, new rectangle(nx, ny, pngsize.width, pngsize.height),
        0, 0, img.width, img.height, graphicsunit.pixel);
 
      g.dispose();
 
      // 以下代码为保存图片时,设置压缩质量
      encoderparameters encoderparams = new encoderparameters();
      long[] quality = new long[1];
      quality[0] = 100;
 
      encoderparameter encoderparam = new encoderparameter(system.drawing.imaging.encoder.quality, quality);
      encoderparams.param[0] = encoderparam;
 
      //获得包含有关内置图像编码解码器的信息的imagecodecinfo 对象。
      imagecodecinfo[] arrayici = imagecodecinfo.getimageencoders();
      imagecodecinfo jpegici = null;
      for (int x = 0; x < arrayici.length; x++)
      {
        if (arrayici[x].formatdescription.equals("jpeg"))
        {
          jpegici = arrayici[x];//设置jpeg编码
          break;
        }
      }
 
      if (jpegici != null)
      {
        outbmp.save(file, jpegici, encoderparams);
      }
      else
      {
        outbmp.save(file, thisformat);
      }
 
      img.dispose();
      outbmp.dispose();
 
      system.io.file.delete(strtempfile);
    }
    #endregion
 
    #region 得到指定mimetype的imagecodecinfo
    /// <summary>
    /// 保存jpg时用
    /// </summary>
    /// <param name="mimetype"> </param>
    /// <returns>得到指定mimetype的imagecodecinfo </returns>
    private imagecodecinfo getcodecinfo(string mimetype)
    {
      imagecodecinfo[] codecinfo = imagecodecinfo.getimageencoders();
      foreach (imagecodecinfo ici in codecinfo)
      {
        if (ici.mimetype == mimetype) return ici;
      }
      return null;
    }
    #endregion
 
    #region 保存为jpeg格式,支持压缩质量选项
    /// <summary>
    /// 保存为jpeg格式,支持压缩质量选项
    /// </summary>
    /// <param name="sourcefile"></param>
    /// <param name="filename"></param>
    /// <param name="qty"></param>
    /// <returns></returns>
    public bool kisaveasjpeg(string sourcefile, string filename, int qty)
    {
      bitmap bmp = new bitmap(sourcefile);
 
      try
      {
        encoderparameter p;
        encoderparameters ps;
 
        ps = new encoderparameters(1);
 
        p = new encoderparameter(system.drawing.imaging.encoder.quality, qty);
        ps.param[0] = p;
 
        bmp.save(filename, getcodecinfo("image/jpeg"), ps);
 
        bmp.dispose();
 
        return true;
      }
      catch
      {
        bmp.dispose();
        return false;
      }
 
    }
    #endregion
 
    #region 将图片压缩到指定大小
    /// <summary>
    /// 将图片压缩到指定大小
    /// </summary>
    /// <param name="filename">待压缩图片</param>
    /// <param name="size">期望压缩后的尺寸</param>
    public void compressphoto(string filename, int size)
    {
      if (!system.io.file.exists(filename))
        return;
 
      int ncount = 0;
      system.io.fileinfo ofile = new system.io.fileinfo(filename);
      long nlen = ofile.length;
      while (nlen > size * 1024 && ncount < 10)
      {
        string dir = ofile.directory.fullname;
        string tempfile = system.io.path.combine(dir, guid.newguid().tostring() + "." + ofile.extension);
        ofile.copyto(tempfile, true);
 
        kisaveasjpeg(tempfile, filename, 70);
 
        try
        {
          system.io.file.delete(tempfile);
        }
        catch { }
 
        ncount++;
 
        ofile = new system.io.fileinfo(filename);
        nlen = ofile.length;
      }
    }
    #endregion
 
    #endregion
 
 
    #region common method
 
    /// <summary>
    /// 图片上传错误编码
    /// </summary>
    /// <param name="code"></param>
    /// <returns></returns>
    private string getcodemessage(int code)
    {
      var dic = new dictionary<int, string>(){
    {0,"系统配置错误"},
    {1,"上传图片成功"},
    {2,string.format( "对不起,上传格式错误!请上传{0}格式图片",setallowformat)},
    {3,string.format("超过文件上传大小,不得超过{0}m",setallowsize)},
    {4,"未上传文件"},
    {5,""},
    {6,"缩略图长度和宽度配置错误"},
    {7,"检测图片宽度限制"}
     };
      return dic[code];
    }
    private void tryerror(responsemessage rm, int code)
    {
      rm.iserror = true;
      rm.message = getcodemessage(code);
    }
    private void tryerror(responsemessage rm, string message)
    {
      rm.iserror = true;
      rm.message = message;
    }
    #endregion
 
    #region models
    public enum cutmode
    {
      /// <summary>
      /// 根据高宽剪切
      /// </summary>
      cutwh = 1,
      /// <summary>
      /// 根据宽剪切
      /// </summary>
      cutw = 2,
      /// <summary>
      /// 根据高剪切
      /// </summary>
      cuth = 3,
      /// <summary>
      /// 缩放不剪裁
      /// </summary>
      cutno = 4
    }
    public class responsemessage
    {
      /// <summary>
      /// 是否遇到错误
      /// </summary>
      public bool iserror { get; set; }
      /// <summary>
      /// web路径
      /// </summary>
      public string webpath { get; set; }
      /// <summary>
      /// 文件物理路径
      /// </summary>
      public string filepath { get; set; }
      /// <summary>
      /// 反回消息
      /// </summary>
      public string message { get; set; }
      /// <summary>
      /// 文件大小
      /// </summary>
      public double size { get; set; }
      /// <summary>
      /// 图片名
      /// </summary>
      public string filename { get; set; }
      /// <summary>
      /// 图片目录
      /// </summary>
      public string directory
      {
        get
        {
          if (webpath == null) return null;
          return webpath.replace(filename, "");
        }
      }
      /// <summary>
      /// 缩略图路径
      /// </summary>
      public string smallpath(int index)
      {
        return string.format("{0}{1}_{2}{3}", directory, path.getfilenamewithoutextension(filename), index, path.getextension(filename));
      }
    }
    #endregion
  }
 
}