ASP.NET 간단 하고 기능 이 완 비 된 사진 업로드 도구 류(워 터 마크,미리 보기,재단 등)

사용 방법:

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

 효과:

 원본 코드:

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

좋은 웹페이지 즐겨찾기