上传图片2(接上一篇)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;

namespace PacificBase.Common
{
public class UploadFile
{
#region 属性
/// <summary>
/// 大图文件夹名称
/// </summary>
public static string BigFolderName = "BigImage";
/// <summary>
/// 小图文件夹名称
/// </summary>
public static string SmallFolderName = "SmallImage";
/// <summary>
/// 图片保存路径
/// </summary>
public static string SavePath = Utils.GetConfig("FilePath");
/// <summary>
/// 文件类型
/// </summary>
public static string fileType = Utils.GetConfig("ImageType");
#endregion

#region 获取上传文件基类对象

public static string UpLoadImage(HttpPostedFile IconPath)
{
HttpPostedFileBase baseFileType = new HttpPostedFileWrapper(IconPath) as HttpPostedFileBase;
return UpLoadImage(baseFileType);
}
/// <summary>
///
/// </summary>
/// <param name="IconPath"></param>
/// <param name="isCreateThumbnail">是否生成缩略图</param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="mode"></param>
/// <param name="isReturnBigWidthHeight">是否返回图片的宽、高</param>
/// <returns></returns>
public static PicUploadResult UpLoadImage(HttpPostedFile IconPath, bool isCreateThumbnail, int width, int height, string mode,bool isReturnBigWidthHeight)
{
HttpPostedFileBase baseFileType = new HttpPostedFileWrapper(IconPath) as HttpPostedFileBase;
return UpLoadImage(baseFileType, isCreateThumbnail, width, height, mode, isReturnBigWidthHeight);
}
#endregion

#region 图片上传
/// <summary>
/// 图片上传
/// </summary>
/// <param name="IconPath"></param>
/// <returns></returns>
public static string UpLoadImage(HttpPostedFileBase IconPath)
{
if (IconPath.ContentLength <= 0) { return ""; }

//图片保存路径
string fileName = "";
string SavePath = Utils.GetConfig("FilePath");
string SavePathFolder = DateTime.Today.ToString("yyyyMM");

if (!System.IO.Directory.Exists(SavePath + SavePathFolder))
{
System.IO.Directory.CreateDirectory(SavePath + SavePathFolder);
}

if (IconPath.FileName != "")
{
int i = IconPath.FileName.LastIndexOf(".");
string UpLoadFileExt = "." + IconPath.FileName.Substring(i + 1);
fileName = Utils.GetRamCode() + UpLoadFileExt;
string imageType = Utils.GetConfig("ImageType");
//是定义的图片类型
if (imageType.IndexOf(UpLoadFileExt + ",") >= 0)
{
try
{
FileStream fs1 = new FileStream(string.Format("{0}{1}\{2}", SavePath, SavePathFolder, fileName), System.IO.FileMode.Create);
byte[] bytes = new byte[IconPath.InputStream.Length];
IconPath.InputStream.Read(bytes, 0, bytes.Length);

// 设置当前流的位置为流的开始
IconPath.InputStream.Seek(0, SeekOrigin.Begin);

fs1.Write(bytes, 0, bytes.Length);
fs1.Close();
}
catch (Exception ex)
{
return ex.Message;
}
}
}
return string.Format("{0}/{1}", SavePathFolder, fileName);
}

/// <summary>
/// 图片上传
/// </summary>
/// <param name="IconPath">图片文件对象</param>
/// <param name="isCreateThumbnail">是否创建缩略图</param>
/// <param name="width">宽</param>
/// <param name="height">高</param>
/// <param name="mode">模式 HW:指定高宽缩放(可能变形)、W:指定宽、高按比例、 H:指定高、宽按比例、Cut:指定高宽裁减(不变形)</param>
/// <param name="isReturnBigWidthHeight">是否返回图片的宽、高</param>
/// <returns></returns>
public static PicUploadResult UpLoadImage(HttpPostedFileBase IconPath, bool isCreateThumbnail, int width, int height, string mode, bool isReturnBigWidthHeight)
{
PicUploadResult result = new PicUploadResult();
result.IsScuess = false;

#region 1.有效性验证
if (IconPath.ContentLength <= 0) { return result; }
if (string.IsNullOrEmpty(IconPath.FileName)) { return result; }

int i = IconPath.FileName.LastIndexOf(".");
string UpLoadFileExt = "." + IconPath.FileName.Substring(i + 1);
//不是定义的文件类型
if (fileType.IndexOf(UpLoadFileExt + ",") < 0) { return result; }
#endregion

#region 2.生成文件名以及创建文件存放目录
//文件名
string fileName = BigFolderName + "_" + Utils.GetRamCode() + UpLoadFileExt;
//年月文件夹
string SavePathFolder = DateTime.Today.ToString("yyyyMM");
//目录路径
string directoryPath = SavePath+ SavePathFolder;

if (!System.IO.Directory.Exists(directoryPath)) { System.IO.Directory.CreateDirectory(directoryPath); }
#endregion

//原图路径
string originalImagePath = string.Format("{0}{1}\{2}", SavePath, SavePathFolder, fileName);

#region 3.上传文件到指定目录
try
{
FileStream fs1 = new FileStream(originalImagePath, System.IO.FileMode.Create);
byte[] bytes = new byte[IconPath.InputStream.Length];
IconPath.InputStream.Read(bytes, 0, bytes.Length);

// 设置当前流的位置为流的开始
IconPath.InputStream.Seek(0, SeekOrigin.Begin);

fs1.Write(bytes, 0, bytes.Length);
fs1.Close();

result.BigPicturePath = string.Format("{0}/{1}", SavePathFolder, fileName);

#region 需要返回大图的宽高
if (isReturnBigWidthHeight)
{
var img = System.Drawing.Image.FromStream(IconPath.InputStream);
result.BigPicWidth = img.Width;
result.BigPicHeight = img.Height;
}
#endregion

#region 需要创建缩略图
if (isCreateThumbnail)
{
result.SmallPicturePath = string.Format("{0}/{1}", SavePathFolder, fileName.Replace(BigFolderName, SmallFolderName));
Thread thread = new Thread(() =>
{
string thumbnailPath = string.Format("{0}\{1}\{2}", SavePath, SavePathFolder, fileName.Replace(BigFolderName, SmallFolderName));

MakeThumbnailExt(originalImagePath, thumbnailPath, width, height, mode);
});
thread.Start();
}
#endregion

result.IsScuess = true;
}
catch (Exception ex)
{
ObjectHelper.SaveLog("上传图片方法:UpLoadImage异常", ex);
}
#endregion

return result;
}
#endregion

#region 生成缩略图
/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="originalImagePath">原图路径(物理路径)</param>
/// <param name="thumbnailPath">缩略图路径(物理路径)</param>
/// <param name="width">缩略图宽度</param>
/// <param name="height">缩略图高度</param>
/// <param name="mode">生成缩略图的方式</param>
public static string MakeThumbnailExt(string originalImagePath, string thumbnailPath, int width, int height, string mode)
{
System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

int towidth = width;
int toheight = height;

int x = 0;
int y = 0;
int ow = originalImage.Width;
int oh = originalImage.Height;

switch (mode)
{
case "HW"://指定高宽缩放(可能变形)
break;
case "W"://指定宽,高按比例
if (originalImage.Width <= width)
{
towidth = ow;
toheight = oh;
}
else
{
toheight = originalImage.Height * width / originalImage.Width;
}
break;
case "H"://指定高,宽按比例
if (originalImage.Height <= height)
{
towidth = ow;
toheight = oh;
}
else
{
towidth = originalImage.Width * height / originalImage.Height;
}
break;
case "Cut"://指定高宽裁减(不变形)
if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
{
oh = originalImage.Height;
ow = originalImage.Height * towidth / toheight;
y = 0;
x = (originalImage.Width - ow) / 2;
}
else
{
ow = originalImage.Width;
oh = originalImage.Width * height / towidth;
x = 0;
y = (originalImage.Height - oh) / 2;
}
break;
default:
break;
}

//新建一个bmp图片
System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

//新建一个画板
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

//清空画布并以透明背景色填充
g.Clear(System.Drawing.Color.Transparent);

//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);

try
{
string filePath = thumbnailPath.Substring(0, thumbnailPath.LastIndexOf('\') + 1);
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
//以jpg格式保存缩略图
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (System.Exception e)
{
ObjectHelper.SaveLog("生成缩略图 MakeThumbnail方法异常", e);
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
return thumbnailPath;
}
#endregion

#region 上传HTML
/// <summary>
/// 上传HTML
/// </summary>
/// <param name="IconPath"></param>
/// <returns></returns>
public static string UpLoadHtml(HttpPostedFileBase Path, string Type)
{
if (Path.ContentLength <= 0)
{
return "";
}

//Word保存路径
string fileName = "";
string SavePath = Utils.GetConfig("FilePath");
string SavePathFolder = DateTime.Today.ToString("yyyyMM");

if (!System.IO.Directory.Exists(SavePath + SavePathFolder))
{
System.IO.Directory.CreateDirectory(SavePath + SavePathFolder);
}

if (Path.FileName != "")
{
int i = Path.FileName.LastIndexOf(".");
string UpLoadFileExt = "." + Path.FileName.Substring(i + 1);
fileName = Utils.GetRamCode() + UpLoadFileExt;


if (Type.IndexOf(UpLoadFileExt + ",") >= 0)
{
try
{
FileStream fs1 = new FileStream(string.Format("{0}{1}\{2}", SavePath, SavePathFolder, fileName), System.IO.FileMode.Create);
byte[] bytes = new byte[Path.InputStream.Length];
Path.InputStream.Read(bytes, 0, bytes.Length);

// 设置当前流的位置为流的开始
Path.InputStream.Seek(0, SeekOrigin.Begin);

fs1.Write(bytes, 0, bytes.Length);
fs1.Close();
}
catch (Exception ex)
{
return ex.Message;
}
return string.Format("{0}/{1}", SavePathFolder, fileName);
}
else
{
return "";
}
}
return "";
}

public static string UpLoadHtml(HttpPostedFile Path, string Type)
{
HttpPostedFileBase baseFileType = new HttpPostedFileWrapper(Path) as HttpPostedFileBase;
return UpLoadHtml(baseFileType, Type);
}
#endregion
}

#region 文件操作结果对象
/// <summary>
/// 文件操作结果基类
/// </summary>
public class FileResult
{
/// <summary>
/// 是否成功
/// </summary>
public bool IsScuess { get; set; }
/// <summary>
/// 错误状态码
/// </summary>
public int ErrorStatus { get; set; }
}
/// <summary>
/// 图片上传操作结果类
/// </summary>
public class PicUploadResult : FileResult
{
/// <summary>
/// 大图路径
/// </summary>
public string BigPicturePath { get; set; }
/// <summary>
/// 小图路径
/// </summary>
public string SmallPicturePath { get; set; }
/// <summary>
/// 大图宽度
/// </summary>
public int BigPicWidth { get; set; }
/// <summary>
/// 大图高度
/// </summary>
public int BigPicHeight { get; set; }
}
#endregion
}

原文地址:https://www.cnblogs.com/ztf20/p/9886110.html