ASP.NET简单好用功能齐全图片上传工具类(水印、

编程学习 2021-07-04 22:41www.dzhlxh.cn编程入门
这篇文章主要介绍了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";
      / 

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板