[C#.Net] 壓縮圖片,指定JPG的壓縮品質

Set JPEG Compression Level

有時候為了改善網站效能,需要把圖片壓縮一下

微軟MSDN已有文章:How to: Set JPEG Compression Level

很擔心會下架,本文算是備份一下

專案為Console,.Net Framework 4.8

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1_PicCompressTest
{
    class Program
    {
        static void Main(string[] args)
        {
              
            string imgSourceFilePath = @"S:\kv_1660x664.png";
            FileInfo imgFile = new FileInfo(imgSourceFilePath);
            if (imgFile.Length > 100 * 1024 )
            {//圖片檔案大小超過100KB
                //壓縮圖片 
                string outJpgFilePath = System.IO.Path.GetFileNameWithoutExtension(imgSourceFilePath) + "_90.jpg";//壓縮後的檔名
                //壓縮後儲存目錄
                string dir = @"S:\";
                VaryQualityLevel(imgSourceFilePath, System.IO.Path.Combine(dir, outJpgFilePath),  90L);

            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="imgSourceFilePath"></param>
        /// <param name="outJpgFilePath"></param>
        /// <param name="qualityLevel">數字愈低,破壞性壓縮愈大</param>
        private static void VaryQualityLevel(string imgSourceFilePath, string outJpgFilePath,long qualityLevel = 90L)
        {
            
            using (Bitmap bmp1 = new Bitmap(imgSourceFilePath))
            {
                ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
                 
                System.Drawing.Imaging.Encoder myEncoder =  System.Drawing.Imaging.Encoder.Quality;//給Compression無效
                 
                EncoderParameters myEncoderParameters = new EncoderParameters(1);
                 myEncoderParameters.Param[0]= new EncoderParameter(myEncoder, qualityLevel);  
                bmp1.Save(outJpgFilePath, jpgEncoder, myEncoderParameters);
            }//end using
            
        }
        private static ImageCodecInfo GetEncoder(ImageFormat format)
        { 
            ImageCodecInfo codec =  ImageCodecInfo.GetImageDecoders().Where(m => m.FormatID == format.Guid).FirstOrDefault();
            if (codec==null)
            {
                return null;
            } 
            return codec;
             
        }
    }
}