文章内容
2017/11/4 13:43:51,作 者: 黄兵
图片上传及压缩处理
压缩类 -- ImageThumbnail ,可按大小、比例进行压缩
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
namespace cw.doctor.Core.Images
{
public class ImageThumbnail
{
public Image ResourceImage;
private int ImageWidth;
private int ImageHeight;
public string ErrorMessage;
public ImageThumbnail(string ImageFileName)
{
ResourceImage = Image.FromFile(ImageFileName);
ErrorMessage = "";
}
public bool ThumbnailCallback()
{
return false;
}
// 方法1,按大小
public bool ReducedImage(int Width, int Height, string targetFilePath)
{
try
{
Image ReducedImage;
Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);
ReducedImage = ResourceImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);
ReducedImage.Save(@targetFilePath, ImageFormat.Jpeg);
ReducedImage.Dispose();
return true;
}
catch (Exception e)
{
ErrorMessage = e.Message;
return false;
}
}
// 方法2,按百分比 缩小60% Percent为0.6 targetFilePath为目标路径
public bool ReducedImage(double Percent, string targetFilePath)
{
try
{
Image ReducedImage;
Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);
ImageWidth = Convert.ToInt32(ResourceImage.Width * Percent);
ImageHeight = (ResourceImage.Height) * ImageWidth / ResourceImage.Width;//等比例缩放
ReducedImage = ResourceImage.GetThumbnailImage(ImageWidth, ImageHeight, callb, IntPtr.Zero);
ReducedImage.Save(@targetFilePath, ImageFormat.Jpeg);
ReducedImage.Dispose();
return true;
}
catch (Exception e)
{
ErrorMessage = e.Message;
return false;
}
}
}
}
文件上传接口
public ActionResult upload(string tel)
{
if (Request.Files.Count == 0)
{
return base.Error("文件不存在!");
}
List<string> lst = new List<string>();
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
string path = AppDomain.CurrentDomain.BaseDirectory;
var filePath = $"upload/Medical/{tel}/{DateTime.Now.ToString("yyyyMM")}";
if (!Directory.Exists(Path.Combine(path, filePath)))
{
Directory.CreateDirectory(Path.Combine(path, filePath));
}
var guid = Guid.NewGuid().ToString();
string fileName = $"{filePath}/{guid}.{file.FileName.Substring(file.FileName.LastIndexOf(".") + 1)}";
file.SaveAs(path + fileName);
ImageThumbnail img = new ImageThumbnail(path + fileName);
img.ReducedImage(242, 200, $"{path + filePath}/{guid}_2.{file.FileName.Substring(file.FileName.LastIndexOf(".") + 1)}");//0.4表示缩小40%
img.ResourceImage.Dispose(); //这里要释放一下
lst.Add($"/{fileName}");
}
return Success(lst);
}
评论列表