悠悠楠杉
ASP.NET中实现固定比例裁剪缩略图的方法
引言
1. 前提条件
- 确保你的ASP.NET项目已安装必要的NuGet包,如
System.Drawing.Common
用于处理图像。 - 了解基本的ASP.NET MVC或ASP.NET Core知识。
2. 创建Action Filter用于图片处理
在ASP.NET MVC或ASP.NET Core中,可以创建一个自定义的Action Filter来处理图片的上传和裁剪操作。以下是创建这样一个Action Filter的步骤:
2.1 定义Action Filter
在Filters
文件夹中(如果没有则创建),添加一个新的类ImageResizerFilterAttribute
:
```csharp
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.Mvc;
using System.Web;
public class ImageResizerFilterAttribute : ActionFilterAttribute
{
public int MaxWidth { get; set; } = 800;
public int MaxHeight { get; set; } = 600;
public string OutputFormat { get; set; } = "Jpeg";
public string FolderPath { get; set; } = "~/Content/ResizedImages/";
public string OriginalExtension { get; set; } = ".jpg";
public string ResizedExtension { get; set; } = ".jpg";
public override void OnActionExecuting(ActionExecutingContext context)
{
if (context.HttpContext.Request.Files.Count > 0)
{
var httpPostedFile = context.HttpContext.Request.Files[0];
if (httpPostedFile != null && httpPostedFile.ContentLength > 0)
{
var fileName = Path.GetFileNameWithoutExtension(httpPostedFile.FileName);
var extension = Path.GetExtension(httpPostedFile.FileName);
var outputPath = Path.Combine(Server.MapPath(FolderPath), $"{fileName}_{ResizedExtension}");
using (var image = Image.FromStream(httpPostedFile.InputStream))
{
var resizedImage = ResizeImage(image, MaxWidth, MaxHeight);
resizedImage.Save(outputPath, GetImageFormat(OutputFormat));
}
}
}
}
private ImageResizer ResizeImage(Image image, int maxWidth, int maxHeight)
{
var resizedImage = new Bitmap(maxWidth, maxHeight);
using (var graphics = Graphics.FromImage(resizedImage))
{
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphics.DrawImage(image, 0, 0, maxWidth, maxHeight);
}
return new ImageResizer(resizedImage); // For demonstration, you might not need this in real code.
}
private ImageFormat GetImageFormat(string format) => format switch {
"Jpeg" => ImageFormat.Jpeg,
"Png" => ImageFormat.Png,
_ => ImageFormat.Jpeg // Default to Jpeg if unsupported format is provided
};
}
```
这个ImageResizerFilterAttribute
类会在图片上传时自动对其进行裁剪和缩放,并将结果保存到指定文件夹。通过设置MaxWidth
和MaxHeight
属性,可以控制图片的最大尺寸。此外,通过修改OutputFormat
、FolderPath
等属性可以调整输出格式和保存路径。
2.2 在Controller中使用Action Filter
在Controller中,只需将该Filter应用于需要处理图片上传的Action:csharp
[HttpPost]
[ImageResizerFilter(MaxWidth = 800, MaxHeight = 600, OutputFormat = "Jpeg")]
public ActionResult UploadImage(HttpPostedFileBase file)
{
// 处理文件上传后的逻辑...
}
这里使用了自定义的ImageResizerFilter
来自动处理上传的图片,无需额外编写图像裁剪代码。 此方法的好处是代码复用性强,且能够统一处理不同Controller中的图片上传需求。