不经保存,直接生成上传图片的等比例的高质量缩略图
我们可以使用FileUpload.FileBytes属性直接得到上传文件的字节数组,从而可以直接生成上传文件的缩略图。代码如下:
ASPX 代码
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
String fileExt = System.IO.Path.GetExtension(FileUpload1.FileName);
System.Drawing.Image image = System.Drawing.Image.FromStream(new System.IO.MemoryStream(FileUpload1.FileBytes));
int newWidth = 300, newHeight = 200;
if ((decimal)image.Width / image.Height > (decimal)newWidth / newHeight)
{
newHeight =Convert.ToInt32((decimal)image.Height * newWidth / image.Width);
}
else if ((decimal)image.Width / image.Height < (decimal)newWidth / newHeight)
{
newWidth = Convert.ToInt32((decimal)image.Width * newHeight / image.Height);
}
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(newWidth, newHeight);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, newWidth, newHeight);
g.DrawImage(image, rectDestination, 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);
bmp.Save(Server.MapPath("~/") + DateTime.Now.ToString("yyyyMMddHHmmss") + fileExt);
bmp.Dispose();
image.Dispose();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>不经保存,直接生成上传图片的等比例的高质量缩略图</title>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="上传并生成缩略图" />
</form>
</body>
</html>
补充:Web开发 , ASP.Net ,