原始大圖儲存於固定路徑。前端請求不同尺寸縮圖 (如 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。 |
<img src="<%= PicShow.ViewPIC("200X300", "movie123.jpg") %>" alt="縮圖" />