c# 无损压缩图片,接口传过来的是字节
/// <summary>
/// 无损压缩图片
/// </summary>
/// <param name="content">base64字节流</param>
/// <param name="flag">(数字越小压缩率越高)1-100</param>
/// <param name="size">压缩后图片的最大大小</param>
/// <param name="sfsc">是否是第一次调用</param>
/// <returns></returns>
public static string CompressImage(string content, int flag = 90, int size = 500, bool sfsc = true)
{
//如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
byte[] bytes = Convert.FromBase64String(content);
if (sfsc == true && bytes.Length < size * 1024)
{
return content;
}
MemoryStream stream = new MemoryStream(bytes, 0, bytes.Length);
stream.Write(bytes, 0, bytes.Length);
Image iSource = Image.FromStream(stream);
ImageFormat tFormat = iSource.RawFormat;
int dHeight = iSource.Height / 2;
int dWidth = iSource.Width / 2;
//按比例缩放
Size tem_size = new Size(iSource.Width, iSource.Height);
int sH;
int sW;
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 =CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode =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(Encoder.Quality, qy);
ep.Param[0] = eParam;
//保存在内存流
MemoryStream ms = new MemoryStream();
ms.Position = 0;
string imagebase64 = "";
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(ms, jpegICIinfo, ep);
byte[] arr = new byte[ms.Length];
ms.Read(arr, 0, (int)ms.Length);
imagebase64 = Convert.ToBase64String(arr);
if (arr.Length > 1024 * size)
{
flag -= 10;
CompressImage(content, flag, size, false);
}
}
else
{
ob.Save(ms, tFormat);
byte[] arr = new byte[ms.Length];
ms.Read(arr, 0, (int)ms.Length);
imagebase64 = Convert.ToBase64String(bytes);
}
return imagebase64;
}
catch
{
return imagebase64;
}
finally
{
iSource.Dispose();
ob.Dispose();
ms.Close();
stream.Close();
}
}
写的不咋地,但是能用了。。嘿

浙公网安备 33010602011771号