C# System.Drawing.Graphics 画图后,如何保存一个低质量的图片,一个占用空间较小的图片
2021-01-23 23:12
标签:save 缩放 时间 硬盘 rom mat aging void 高质量 首先要控制图片保存后硬盘后的大小(即占用硬盘的空间,而非尺寸),真正要处理的是控制 System.Drawing.Bitmap.Save 方法的参数。 具体实现如下: C# System.Drawing.Graphics 画图后,如何保存一个低质量的图片,一个占用空间较小的图片 标签:save 缩放 时间 硬盘 rom mat aging void 高质量 原文地址:https://www.cnblogs.com/challengesoflife/p/12059567.htmlprivate void ThumbPicture(Image SourceImage, int TargetWidth,string savePath)
{
int IntWidth; //新的图片宽
int IntHeight; //新的图片高
try
{
int TargetHeight = (int)Math.Round(TargetWidth / (SourceImage.Width * 1.0f / SourceImage.Height));
if (TargetWidth * TargetHeight >= SourceImage.Width * SourceImage.Height)
{
SourceImage.Save(savePath);
SourceImage.Dispose();
return;
}
//计算缩放图片的大小
if (SourceImage.Width > TargetWidth && SourceImage.Height //宽度比目的图片宽度大,长度比目的图片长度小
{
IntWidth = TargetWidth;
IntHeight = (IntWidth * SourceImage.Height) / SourceImage.Width;
}
else if (SourceImage.Width TargetHeight)//宽度比目的图片宽度小,长度比目的图片长度大
{
IntHeight = TargetHeight;
IntWidth = (IntHeight * SourceImage.Width) / SourceImage.Height;
}
else if (SourceImage.Width //长宽比目的图片长宽都小
{
IntHeight = SourceImage.Width;
IntWidth = SourceImage.Height;
}
else//长宽比目的图片的长宽都大
{
IntWidth = TargetWidth;
IntHeight = (IntWidth * SourceImage.Height) / SourceImage.Width;
if (IntHeight > TargetHeight)//重新计算
{
IntHeight = TargetHeight;
IntWidth = (IntHeight * SourceImage.Width) / SourceImage.Height;
}
}
var x = (TargetWidth - IntWidth) / 2;
var y = (TargetHeight - IntHeight) / 2;
using (var newImage = new Bitmap(TargetWidth, TargetHeight))
{
using (var graphic = Graphics.FromImage(newImage))
{
// 核心参数啊,感觉相当于PS保存时间的质量设置参数
Int64 qualityLevel = 80L;
// 高质量
graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
qualityLevel = 100L;
// 低质量
//graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
//graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
//qualityLevel = 60L;
System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
eParams.Param[0]=new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityLevel);
graphic.DrawImage(SourceImage, 0, 0, TargetWidth, TargetHeight);
SourceImage.Dispose();
// 使用控制图片质量的保存方式
//newImage.Save(savePath);
newImage.Save(savePath, codec, eParams);
}
}
}
catch (Exception ex)
{
}
}
文章标题:C# System.Drawing.Graphics 画图后,如何保存一个低质量的图片,一个占用空间较小的图片
文章链接:http://soscw.com/index.php/essay/46069.html