C# 无损压缩图片
转载
1 /// <summary> 2 /// 降低图片质量 3 /// </summary> 4 /// <param name="sFile">文件流</param> 5 /// <param name="flag">压缩倍率(1-100)</param> 6 /// <param name="size">输出最大流尺寸(单位:MB)</param> 7 /// <param name="sfsc">是否第一次执行方法</param> 8 /// <returns></returns> 9 privatestaticStream ReducePictureQuality(Stream sFile, int flag =90, int size =1, bool sfsc =true) 10 { 11 12 MemoryStream outStream =newMemoryStream(); 13 14 //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true 15 16 //FileInfo firstFileInfo = new FileInfo(sFile); 17 18 if (sfsc ==true&& sFile.Length < size *1024*1024) 19 { 20 return sFile; 21 } 22 23 Image iSource =Image.FromStream(sFile); 24 ImageFormat tFormat = iSource.RawFormat; 25 int dHeight = iSource.Height /2; 26 int dWidth = iSource.Width /2; 27 28 int sW =0, sH =0; 29 //按比例缩放 30 Size tem_size =newSize(iSource.Width, iSource.Height); 31 if (tem_size.Width > dHeight || tem_size.Width > dWidth) 32 { 33 if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth)) 34 { 35 sW = dWidth; 36 sH = (dWidth * tem_size.Height) / tem_size.Width; 37 } 38 else 39 { 40 sH = dHeight; 41 sW = (tem_size.Width * dHeight) / tem_size.Height; 42 } 43 } 44 else 45 { 46 sW = tem_size.Width; 47 sH = tem_size.Height; 48 } 49 Bitmap ob =newBitmap(dWidth, dHeight); 50 Graphics g =Graphics.FromImage(ob); 51 g.Clear(Color.WhiteSmoke); 52 53 g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; 54 55 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; 56 57 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; 58 59 g.DrawImage(iSource, newRectangle((dWidth - sW) /2, (dHeight - sH) /2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel); 60 61 g.Dispose(); 62 63 //以下代码为保存图片时,设置压缩质量 64 65 EncoderParameters ep =newEncoderParameters(); 66 67 long[] qy =newlong[1]; 68 69 qy[0] = flag;//设置压缩的比例1-100 70 71 EncoderParameter eParam =newEncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); 72 73 ep.Param[0] = eParam; 74 75 try 76 { 77 ImageCodecInfo[] arrayICI =ImageCodecInfo.GetImageEncoders(); 78 79 ImageCodecInfo jpegICIinfo =null; 80 81 for (int x =0; x < arrayICI.Length; x++) 82 { 83 if (arrayICI[x].FormatDescription.Equals("JPEG")) 84 { 85 jpegICIinfo = arrayICI[x]; 86 break; 87 } 88 } 89 90 if (jpegICIinfo !=null) 91 { 92 ob.Save(outStream, jpegICIinfo, ep);//dFile是压缩后的新路径//// 93 //FileInfo fi = new FileInfo(); 94 if (outStream.Length >1024*1024* size) 95 { 96 flag = flag -10; 97 98 ReducePictureQuality(outStream, flag, size, false); 99 100 } 101 102 } 103 104 else 105 { 106 107 ob.Save(outStream, tFormat); 108 109 } 110 111 return outStream; 112 113 } 114 115 catch (Exception ex) 116 { 117 returnnull; 118 } 119 120 finally 121 { 122 iSource.Dispose(); 123 ob.Dispose(); 124 125 } 126 } 127