1. 程式人生 > 實用技巧 >高強度不失真線上壓縮圖片(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); }