.net压缩图片质量(附demo)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.net压缩图片质量(附demo)相关的知识,希望对你有一定的参考价值。
private void CompressedImage(string fileName, long quality) { FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); Byte[] bytePic = new Byte[fs.Length]; fs.Read(bytePic, 0, bytePic.Length); MemoryStream stream = new MemoryStream(bytePic); Bitmap bmp = (Bitmap)Image.FromStream(stream); ImageCodecInfo myImageCodecInfo = ImageCodecInfo.GetImageEncoders()[1]; //如果下面遍历没有这种图片格式,就默认为jpeg ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders(); for (int j = 0; j < encoders.Length; j++) { if (encoders[j].MimeType == "image/jpeg") { myImageCodecInfo = encoders[j]; break; } } System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; //要操作的是质量 EncoderParameters myEncoderParameters = new EncoderParameters(1); //一个成员,只处理质量 EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, quality); //0为最差质量,100为最好,注意是long类型 myEncoderParameters.Param[0] = myEncoderParameter; Size s = new Size(bmp.Width, bmp.Height); Bitmap newBmp = new Bitmap(bmp, s); MemoryStream ms = new MemoryStream(); newBmp.Save(ms, myImageCodecInfo, myEncoderParameters); //压缩后的流保存到ms //从流中还原图片 Image image = Image.FromStream(ms); string curDirectory = Path.GetDirectoryName(Assembly.GetCallingAssembly().GetModules()[0].FullyQualifiedName) + "\\\\"; //保存图片 image.Save(curDirectory + "pic.jpg"); fs.Dispose(); stream.Dispose(); newBmp.Dispose(); ms.Dispose(); }
以上是关于.net压缩图片质量(附demo)的主要内容,如果未能解决你的问题,请参考以下文章
winserver的consul部署实践与.net core客户端使用(附demo源码)
winserver的consul部署实践与.net core客户端使用(附demo源码)