在处理传统 ASP.NET WebForms 项目时,图片上传是常见需求。很多时候我们不仅需要保存原图,还需要自动生成缩略图以便在列表页展示。下面分享一个基于 System.Drawing 的实现方案,重点在于保持宽高比和释放资源。
核心逻辑说明
- 格式校验:通过 ContentType 判断是否为图片类型,避免非图片文件被处理。
- 尺寸计算:读取原图宽高,根据预设的缩略图最大宽度(如 100px)按比例反推高度,确保不变形。
- 图像渲染:使用 Graphics 对象进行绘制,开启高质量插值和平滑模式,提升视觉效果。
- 资源管理:务必在 finally 块中释放 Image、Graphics 等对象,防止内存泄漏。
代码实现
以下是具体的事件处理方法。注意文件名生成逻辑使用了毫秒级时间戳,在高并发场景下可能存在冲突风险,生产环境建议结合 GUID 或哈希值优化。
private void btnUploadPicture_Click(object sender, System.EventArgs e)
{
// 检查上传文件的格式是否有效
if (this.UploadFile.PostedFile.ContentType.ToLower().IndexOf("image") < 0)
{
Response.Write("上传图片格式无效!");
return;
}
// 生成原图
Byte[] oFileByte = new byte[this.UploadFile.PostedFile.ContentLength];
System.IO.Stream oStream = this.UploadFile.PostedFile.InputStream;
System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);
int oWidth = oImage.Width; // 原图宽度
int oHeight = oImage.Height; // 原图高度
int tWidth = 100; // 设置缩略图初始宽度
int tHeight = 100; // 设置缩略图初始高度
// 按比例计算出缩略图的宽度和高度
if (oWidth >= oHeight)
{
tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
}
{
tWidth = ()Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
}
Bitmap tImage = Bitmap(tWidth, tHeight);
Graphics g = Graphics.FromImage(tImage);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.Clear(Color.Transparent);
g.DrawImage(oImage, Rectangle(, , tWidth, tHeight), Rectangle(, , oWidth, oHeight), GraphicsUnit.Pixel);
oFullName = Server.MapPath() + + + DateTime.Now.ToShortDateString().Replace(, ) + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + ;
tFullName = Server.MapPath() + + + DateTime.Now.ToShortDateString().Replace(, ) + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + ;
{
oImage.Save(oFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
tImage.Save(tFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
(Exception ex)
{
ex;
}
{
oImage.Dispose();
g.Dispose();
tImage.Dispose();
}
}

