上传图片时需要将图片进行按照宽度缩放,直接调用方法就可以上传图片
/// <summary>
/// 图片按宽带等比缩放
/// </summary>
/// <param name="fromFile">原图Stream对象</param>
/// <param name="savePath">缩略图存放地址</param>
/// <param name="targetWidth">指定的最大宽度</param>
public static void ZoomAuto(System.IO.Stream fromFile, string savePath, System.Double targetWidth)
{
//创建目录
string dir = Path.GetDirectoryName(savePath);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
//原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true);
Double targetHeight = 0;
if (initImage.Width <= targetWidth)
{
targetHeight = initImage.Height;
}
else
{
Double w = initImage.Width;
Double h = initImage.Height;
Double wRatio = targetWidth / (w * 1.0);
targetHeight = h * wRatio;
}
//原图宽高均小于模版,不作处理,直接保存
if (initImage.Width <= targetWidth)
{
//保存
initImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
else
{
//缩略图宽、高计算
double newWidth = initImage.Width;
double newHeight = initImage.Height;
//宽大于高或宽等于高(横图或正方)
if (initImage.Width > initImage.Height || initImage.Width == initImage.Height)
{
//如果宽大于模版
if (initImage.Width > targetWidth)
{
//宽按模版,高按比例缩放
newWidth = targetWidth;
newHeight = initImage.Height * (targetWidth / initImage.Width);
}
}
//高大于宽(竖图)
else
{
//如果高大于模版
if (initImage.Height > targetHeight)
{
//高按模版,宽按比例缩放
newHeight = targetHeight;
newWidth = initImage.Width * (targetHeight / initImage.Height);
}
}
//生成新图
//新建一个bmp图片
System.Drawing.Image newImage = new System.Drawing.Bitmap((int)newWidth, (int)newHeight);
//新建一个画板
System.Drawing.Graphics newG = System.Drawing.Graphics.FromImage(newImage);
//设置质量
newG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
newG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//置背景色
newG.Clear(Color.White);
//画图
newG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, newImage.Width, newImage.Height), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);
//保存缩略图
newImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
//释放资源
newG.Dispose();
newImage.Dispose();
initImage.Dispose();
}
}
评论列表: