45fan.com - ··¹Íø

ËÑË÷: ÄúµÄλÖãºÖ÷Ò³ > µçÄÔƵµÀ > ±à³Ì´úÂë > ÔĶÁ×ÊѶ£ºASP.NETͼƬÉÏ´«ÀàµÄʹÓ÷½·¨£¨Ë®Ó¡¡¢ËõÂÔͼ¡¢²Ã¼ôµÈ£©

ASP.NETͼƬÉÏ´«ÀàµÄʹÓ÷½·¨£¨Ë®Ó¡¡¢ËõÂÔͼ¡¢²Ã¼ôµÈ£©

2015-06-29 13:52:18 À´Ô´:www.45fan.com ¡¾´ó ÖРС¡¿

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

Ч¹û£º

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

±¾ÎĵØÖ·£ºhttp://www.45fan.com/bcdm/12910.html
Tags£º ¼òµ¥ ASP.NET ¹¦ÄÜÆëÈ«
±à¼­£ºÂ··¹Íø
ÍƹãÄÚÈÝ
ÍƼöÔĶÁ
ÈÈÃÅÍƼö
ÍƼöÎÄÕÂ
¹ØÓÚÎÒÃÇ | ÁªÏµÎÒÃÇ | ÓÑÇéÁ´½Ó | ÍøÕ¾µØͼ | Sitemap | App | ·µ»Ø¶¥²¿