使用C#压缩图片
下列代码为使用byte字节数组压缩
注释的是使用文件路径
/// <summary>
/// 压缩图片
/// </summary>
/// <param name="buffer">图片数据</param>
/// <param name="outPath">保存位置</param>
/// <param name="flag">图片质量</param>
/// <returns></returns>
public static bool ReduceImage(byte[] buffer ,string outPath, int flag)
{
MemoryStream ms = new MemoryStream(buffer);//使用byte
Image iSource = Image.FromStream(ms);//如果使用路径 就用下面一个
//Image iSource = Image.FromFile(path);
ImageFormat tFormat = iSource.RawFormat;
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1];
qy[0] = flag;
EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
ep.Param[0] = eParam;
try
{
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageDecoders();
ImageCodecInfo jpegICIinfo = null;
for (int x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICIinfo = arrayICI[x];
break;
}
}
if (jpegICIinfo != null)
iSource.Save(outPath, jpegICIinfo, ep);
else
iSource.Save(outPath, tFormat);
return true;
}
catch (Exception ex)
{
return false;
}
finally
{
iSource.Dispose();
}
}