C#对照片流进行压缩
有时候在开发项目时会遇到限制图片大小的应用场景,这时候就需要对上传或下载的图片流进行压缩,以达到限制图片大小的目的,具体实现代码如下:
/// <summary>
/// 降低图片质量
/// </summary>
/// <param name="sFile">文件流</param>
/// <param name="flag">压缩倍率(1-100)</param>
/// <param name="size">输出最大流尺寸(单位:MB)</param>
/// <param name="sfsc">是否第一次执行方法</param>
/// <returns></returns>
private static Stream ReducePictureQuality(Stream sFile, int flag = 90, double size = 0.18, bool sfsc = true)
{
MemoryStream outStream = new MemoryStream();
//如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
if (sfsc == true && sFile.Length < size * 1024 * 1024)
{
return sFile;
}
Image iSource = Image.FromStream(sFile);
ImageFormat tFormat = iSource.RawFormat;
int dHeight = iSource.Height / 2;
int dWidth = iSource.Width / 2;
int sW = 0, sH = 0;
//按比例缩放
Size tem_size = new Size(iSource.Width, iSource.Height);
if (tem_size.Width > dHeight || tem_size.Width > dWidth)
{
if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
{
sW = dWidth;
sH = (dWidth * tem_size.Height) / tem_size.Width;
}
else
{
sH = dHeight;
sW = (tem_size.Width * dHeight) / tem_size.Height;
}
}
else
{
sW = tem_size.Width;
sH = tem_size.Height;
}
Bitmap ob = new Bitmap(dWidth, dHeight);
Graphics g = Graphics.FromImage(ob);
g.Clear(Color.WhiteSmoke);
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
g.Dispose();
//以下代码为保存图片时,设置压缩质量
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1];
qy[0] = flag;//设置压缩的比例1-100
EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
ep.Param[0] = eParam;
try
{
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICIinfo = null;
for (int x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICIinfo = arrayICI[x];
break;
}
}
if (jpegICIinfo != null)
{
ob.Save(outStream, jpegICIinfo, ep);//dFile是压缩后的新路径////
//FileInfo fi = new FileInfo();
if (outStream.Length > 1024 * 1024 * size)
{
flag = flag - 10;
ReducePictureQuality(outStream, flag, size, false);
}
}
else
{
ob.Save(outStream, tFormat);
}
return outStream;
}
catch (Exception ex)
{
return null;
}
finally
{
iSource.Dispose();
ob.Dispose();
}
}
注:如果有对上述实例代码不明白的,可以直接在文章下方留言,作者看到了会进行回复和探讨。
版权声明:
作者:兴兴
文章:C#对照片流进行压缩
链接:https://www.networkcabin.com/notes/2552
文章版权归本站所有,未经授权请勿转载。
作者:兴兴
文章:C#对照片流进行压缩
链接:https://www.networkcabin.com/notes/2552
文章版权归本站所有,未经授权请勿转载。
THE END