C# 递归缩小图片

时间:2023-12-19 20:06:26

需求:图片太大,上传到服务器会非常占用服务器空间,而系统又不要求高清图片,于是就通过递归的方式让图片每次减少10%的大小,当图片大小小于100k的时候就保存在本地,核心代码如下:

class Program
{
static void Main(string[] args)
{
byte[] bs = File.ReadAllBytes(@"F:\DSCN0361.JPG");
Image img = zipImage(bs);
//写入本地
img.Save("DSCN0361.JPG");
Console.WriteLine("转换成功");
Console.Read();
} /// <summary>
/// 递归缩小图片,每次缩小到90%大小,当图片大小小于100k时就跳出循环,返回Image对象
/// </summary>
/// <param name="bs"></param>
/// <returns></returns>
static Image zipImage(byte[] bs)
{
//最大100k
if (bs.Length > * )
{
Image img = Image.FromStream(new MemoryStream(bs));
Bitmap b = new Bitmap((int)(img.Width * 0.9), (int)(img.Height * 0.9));
b.SetResolution(, );
Graphics g = Graphics.FromImage(b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle recTo = new Rectangle(, , b.Width, b.Height);//表示目标大小
Rectangle recFrom = new Rectangle(, , img.Width, img.Height);//表示源文件大小
g.DrawImage(img, recTo, recFrom, GraphicsUnit.Pixel);
g.Dispose(); MemoryStream ms = new MemoryStream();
b.Save(ms, ImageFormat.Jpeg);
return zipImage(ms.GetBuffer());
}
else
{
return Image.FromStream(new MemoryStream(bs));
} }
}

重点是方法 zipImage