压缩图片方法
Posted sharestone
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了压缩图片方法相关的知识,希望对你有一定的参考价值。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; using System.Drawing.Imaging; using System.IO; namespace Utility { public static class CompressImage { public static Bitmap PercentImage(Image srcImage) { int newW = srcImage.Width < 1130 ? srcImage.Width : 1130; int newH = int.Parse(Math.Round(srcImage.Height * (double)newW / srcImage.Width).ToString()); try { Bitmap b = new Bitmap(newW, newH); Graphics g = Graphics.FromImage(b); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default; g.DrawImage(srcImage, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, srcImage.Width, srcImage.Height), GraphicsUnit.Pixel); g.Dispose(); return b; } catch (Exception) { return null; } } //将图片按百分比压缩,flag取值1到100,越小压缩比越大 public static bool YaSuo(Image iSource, string outPath, int flag) { 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 { return false; } } } }
以上是关于压缩图片方法的主要内容,如果未能解决你的问题,请参考以下文章
png图片怎么通过代码实现压缩到指定的文件大小,比如5M压缩到200KB,比如用pngquant或imageMagick