这个是未经优化的简单实现
public static SystemDrawingImage GetImageThumb(SystemDrawingImage sourceImg int width int height) { SystemDrawingImage targetImg = new SystemDrawingBitmap(width height); using (SystemDrawingGraphics g = SystemDrawingGraphicsFromImage(targetImg)) { gInterpolationMode = SystemDrawingDrawingDInterpolationModeHigh; gSmoothingMode = SystemDrawingDrawingDSmoothingModeHighQuality; gInterpolationMode = SystemDrawingDrawingDInterpolationModeHighQualityBicubic; gCompositingQuality = SystemDrawingDrawingDCompositingQualityHighQuality; gPixelOffsetMode = SystemDrawingDrawingDPixelOffsetModeHighQuality; gDrawImage(sourceImg new SystemDrawingRectangle( width height) new SystemDrawingRectangle( sourceImgWidth sourceImgHeight) SystemDrawingGraphicsUnitPixel); gDispose(); } return targetImg; }
这个方法比较简单用到的是高质量压缩经过这个方法压缩后K的图片只能压缩到k左右
经过改写代码实现了如下的方法
public Bitmap GetImageThumb(Bitmap mg Size newSize) { double ratio = d; double myThumbWidth = d; double myThumbHeight = d; int x = ; int y = ; Bitmap bp; if ((mgWidth / ConvertToDouble(newSizeWidth)) > (mgHeight / ConvertToDouble(newSizeHeight))) ratio = ConvertToDouble(mgWidth) / ConvertToDouble(newSizeWidth); else ratio = ConvertToDouble(mgHeight) / ConvertToDouble(newSizeHeight); myThumbHeight = MathCeiling(mgHeight / ratio); myThumbWidth = MathCeiling(mgWidth / ratio); Size thumbSize = new Size((int)newSizeWidth (int)newSizeHeight); bp = new Bitmap(newSizeWidth newSizeHeight); x = (newSizeWidth thumbSizeWidth) / ; y = (newSizeHeight thumbSizeHeight); SystemDrawingGraphics g = GraphicsFromImage(bp); gSmoothingMode = SmoothingModeHighQuality; gInterpolationMode = InterpolationModeHighQualityBicubic; gPixelOffsetMode = PixelOffsetModeHighQuality; Rectangle rect = new Rectangle(x y thumbSizeWidth thumbSizeHeight); gDrawImage(mg rect mgWidth mgHeight GraphicsUnitPixel); return bp; }
这样实现的压缩使压缩率大幅度上升其实代码并没有变多少最主要的是在保存的时候要是用jpg格式
如果不指定格式默认使用的是png格式
下面这个是园友写的根据设置图片质量数值来压缩图片的方法
public static bool GetPicThumbnail(string sFile string outPath int flag) { SystemDrawingImage iSource = SystemDrawingImageFromFile(sFile); ImageFormat tFormat = iSourceRawFormat; //以下代码为保存图片时设置压缩质量 EncoderParameters ep = new EncoderParameters(); long[] qy = new long[]; qy[] = flag;//设置压缩的比例 EncoderParameter eParam = new EncoderParameter(SystemDrawingImagingEncoderQuality qy); epParam[] = eParam; try { ImageCodecInfo[] arrayICI = ImageCodecInfoGetImageEncoders(); ImageCodecInfo jpegICIinfo = null; for (int x = ; x < arrayICILength; x++) { if (arrayICI[x]FormatDescriptionEquals("JPEG")) { jpegICIinfo = arrayICI[x]; break; } } if (jpegICIinfo != null) { iSourceSave(outPath jpegICIinfo ep);//dFile是压缩后的新路径 } else { iSourceSave(outPath tFormat); } return true; } catch { return false; } finally { iSourceDispose(); iSourceDispose(); } }