必须先引用命名空间:
using System.IO;
if (FileUpload1.PostedFile.ContentType.ToLower().IndexOf("image") < 0)
...{
FunctionUtility.JavaScriptHelper.Alert("上传图片格式不正确!");
return;
}
//生成原图
Byte[] oFileByte = new Byte[FileUpload1.PostedFile.ContentLength];
Stream oStream = FileUpload1.PostedFile.InputStream;
System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);
//原图宽度和高度
int oWidth = oImage.Width;
int oHeight = oImage.Height;
//设置缩略图的初始宽度和高度
int tWidth = 200;
int tHeight = 200;
//按比例计算出缩略图的宽度和高度
if (oWidth >= oHeight)
...{
tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
}
else
...{
tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
}
//生成缩略图
Bitmap tImage = new 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, new Rectangle(0, 0, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel);
//设置文件名称
string setFileName = FunctionUtility.FileHelper.GetDateTimeFileName()+".jpg";
//保存原图的物理路径
string oFullName = Server.MapPath("/DesignImages/Images/YT/" + setFileName);
//保存缩略图物理路径
string tFullName = Server.MapPath("/DesignImages/Images/SLT/" + setFileName);
//以JPG格式保存图片并释放占用的资源
try
...{
oImage.Save(oFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
tImage.Save(tFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
Image1.Visible = true;
Image2.Visible = true;
Image1.ImageUrl = "/DesignImages/Images/YT/" + setFileName;
Image2.ImageUrl = "/DesignImages/Images/SLT/" + setFileName;
FunctionUtility.JavaScriptHelper.Alert("缩略图生成成功!");
}
catch (Exception oe)
...{
throw oe;
}
finally
...{
oImage.Dispose();
g.Dispose();
tImage.Dispose();
}
本文介绍了一种在C#中生成图片缩略图的方法。首先检查上传文件是否为图片格式,然后读取原始图片并获取其尺寸。接着按比例调整图片大小以创建缩略图,并使用高质量插值法及平滑模式进行绘制。最后将图片保存到指定路径。
3776

被折叠的 条评论
为什么被折叠?



