首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

C# 縮圖多路徑多格式儲存:動態產生指定尺寸 JPEG 縮圖

     編輯:更多程式設計知識

需求

原始大圖儲存於固定路徑。前端請求不同尺寸縮圖 (如 200x300、100x100),若縮圖不存在則即時產生並快取至對應尺寸資料夾,下次直接回傳。

完整類別實作

using System;
using System.Drawing;
using System.Drawing.Imaging;

namespace PubLib
{
    public class PicShow
    {
        // 檢查並回傳縮圖虛擬路徑 (不存在則產生)
        public static string ViewPIC(string picPath, string picName)
        {
            // 根目錄常數 (實際專案請從 Configuration 讀取)
            const string PHYSICS_ROOT = @"C:\WebRoot\"; // 對應 Checks.HM_PHYSICSROOT
            const string BIG_PIC_ROOT = "MoviePIC\Original\"; // 對應 Checks.HM_PICROOTPATH

            string bigPicPath = PHYSICS_ROOT + BIG_PIC_ROOT + picName;
            string smallPicPath = PHYSICS_ROOT + "MoviePIC\" + picPath + @"\" + picName;
            string virtualPath = "MoviePIC/" + picPath + "/" + picName;

            // 大圖不存在或檔名為空 → 使用預設圖
            if (string.IsNullOrEmpty(picName) || !System.IO.File.Exists(bigPicPath))
                picName = "nopic.jpg";

            // 縮圖不存在 → 產生
            if (!System.IO.File.Exists(smallPicPath))
                CreatePIC(picPath, picName);

            return virtualPath;
        }

        // 產生縮圖並儲存為 JPEG
        public static void CreatePIC(string picPath, string picName)
        {
            const string PHYSICS_ROOT = @"C:\WebRoot\";
            const string BIG_PIC_ROOT = "MoviePIC\Original\";

            // 解析尺寸:picPath 格式 "200X300"
            if (string.IsNullOrEmpty(picPath) || !picPath.Contains("X")) return;

            string[] size = picPath.Split('X');
            if (size.Length != 2) return;
            if (!int.TryParse(size[0], out int width) || !int.TryParse(size[1], out int height)) return;

            string bigPic = PHYSICS_ROOT + BIG_PIC_ROOT + picName;
            string smallPic = PHYSICS_ROOT + "MoviePIC\" + picPath + @"\" + picName;

            // 確保目錄存在
            string dir = System.IO.Path.GetDirectoryName(smallPic);
            if (!System.IO.Directory.Exists(dir)) System.IO.Directory.CreateDirectory(dir);

            using (Image bigImg = Image.FromFile(bigPic))
            using (Image smallImg = bigImg.GetThumbnailImage(width, height, null, IntPtr.Zero))
            {
                smallImg.Save(smallPic, ImageFormat.Jpeg);
            }
        }
    }
}

關鍵設計點

點說明
路徑即尺寸資料夾命名為 200X300,直接解析寬高,無需資料庫設定。
快取機制檔案存在即回傳,避免重複產生,降低 CPU/IO。
using 區塊確保 Image 物件正確 Dispose,釋放 GDI+ 資源、檔案鎖定。
GetThumbnailImage快速產生縮圖,但品質較低;高品質需求請用 Graphics.DrawImage + InterpolationMode.HighQualityBicubic。
預設圖大圖缺失時回傳 nopic.jpg,避免 404。

前端使用範例 (ASP.NET)

<img src="<%= PicShow.ViewPIC("200X300", "movie123.jpg") %>" alt="縮圖" />

效能優化建議

  • 背景工作佇列 (Hangfire/Quartz) 預熱熱門尺寸縮圖。
  • CDN 快取虛擬路徑,減少源站壓力。
  • 原始圖存儲於物件存儲 (S3/Blob),縮圖產生後上傳並回傳 CDN URL。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved