高强度不失真在线压缩图片(jpg与png)
结合第三方类库,高强度不失真在线压缩图片,压缩Jpg与Png格式图片。
在线图片压缩,压缩Jpg与Png格式图片。
压缩PNG可使用类库:PNGCompressor
压缩jpg可使用类库:TJCompressor
以下为封装后的部分代码片段。
[HttpPost] public ApiResult ImageCompress(GeneralImageCompressViewModel vm) { if (!ModelState.IsValid) { return this.ModelErrorTextResult(); } int quality = 80; if (vm.QualityType == 1) { quality = 80; } else if (vm.QualityType == 2) { quality = 60; } else if (vm.QualityType == 3) { quality = 40; } else if (vm.QualityType == 4) { quality = 20; } string fileName = Path.GetFileNameWithoutExtension(vm.ImageUrl); string targetUrl = vm.ImageUrl.Replace(fileName, $"{fileName}_compress_{quality}"); string extName = Path.GetExtension(vm.ImageUrl).Replace(".", "").ToLower(); string sourceFullName = UrlOper.MapPath(vm.ImageUrl); string targetFullName = UrlOper.MapPath(targetUrl); bool isSuccess = true; Size newSize = new Size(); try { using (Image img = Image.FromFile(sourceFullName)) { newSize = Commons.EqualRatioSize(img.Width, img.Height, vm.ImgWidth, vm.ImgHeight); using (var bmp = new Bitmap(img, newSize.Width, newSize.Height)) { //压缩PNG if (extName == "png") { string tmpImg = UrlOper.MapPath(vm.ImageUrl.Replace(fileName, $"{fileName}_pngsitesize_{newSize.Width}_{newSize.Height}")); bmp.Save(tmpImg); bmp.Dispose(); var pngCompressor = new PNGCompression.PNGCompressor { PNGToolPath = UrlOper.MapPath("~/content/tools/pngquant"), PNGExeName = "pngquant.exe" }; pngCompressor.CompressImageLossy(tmpImg, targetFullName, new PNGCompression.LossyInputSettings { MinQuality = 0, MaxQuality = (quality + 20) }); System.IO.File.Delete(tmpImg); } //压缩JPG else if (extName == "jpg" || extName == "jpeg") { var jpgCompressor = new MozJpegSharp.TJCompressor(); var compressed = jpgCompressor.Compress(bmp, MozJpegSharp.TJSubsamplingOption.Chrominance420, quality, MozJpegSharp.TJFlags.None); System.IO.File.WriteAllBytes(targetFullName, compressed); } } } if (!System.IO.File.Exists(targetFullName)) { isSuccess = false; } } catch { isSuccess = false; } if (!isSuccess) { return this.Ok(new { IsCompressOK = false }); } long sourceLength = new System.IO.FileInfo(sourceFullName).Length; long targetLength = new System.IO.FileInfo(targetFullName).Length; //如果压缩后更大,则返回原图 if (targetLength > sourceLength) { targetLength = sourceLength; targetUrl = vm.ImageUrl; } var compressRatio = 100 - (int)(((decimal)targetLength / (decimal)sourceLength) * 100m); if (compressRatio == 100) { compressRatio = 99; } string sourceSizeDesc = FileHelper.GetFileSizeDesc(sourceLength); string targetSizeDesc = FileHelper.GetFileSizeDesc(targetLength); object result = new { Source = UrlOper.ResolveClientUrl(vm.ImageUrl), Target = targetUrl, IsCompressOK = true, ImgWidth = newSize.Width, ImgHeight = newSize.Height, SourceSizeDesc = sourceSizeDesc, TargetSizeDesc = targetSizeDesc, CompressRatio = compressRatio }; return this.Ok(result); }
版权声明:本文为immensity原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。