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

C# ASP.NET 產生縮略圖完整範例:FileUpload 上傳、儲存、等比例縮放、存檔

     編輯:更多程式設計知識

ASP.NET WebForms 經典場景:使用者上傳圖片,伺服器端以 System.Drawing 產生固定寬度的等比例縮略圖,並依業務分類 (首頁輪播、週刊推薦、一般列表) 套用不同尺寸規則。

核心程式碼 (Code-behind 片段)

if (fileupload.PostedFile != null)
{
    // 1. 取得副檔名
    string originalName = fileupload.PostedFile.FileName;
    int dotIdx = originalName.LastIndexOf(".");
    string ext = originalName.Substring(dotIdx);

    // 2. 產生唯一檔名:年份天數 + 檔案大小
    DateTime now = DateTime.Now;
    string newName = now.DayOfYear.ToString() + fileupload.PostedFile.ContentLength.ToString();

    // 3. 儲存原圖
    string savePath = Server.MapPath("~/upload/" + newName + ext);
    fileupload.PostedFile.SaveAs(savePath);

    // 4. 產生縮略圖
    System.Drawing.Image img = System.Drawing.Image.FromFile(savePath);
    int width = img.Width, height = img.Height;
    int newWidth, newHeight;

    // 業務尺寸規則
    if (firstpageshow.SelectedValue == "1" && fenlei.SelectedValue == "5")
    { newWidth = 203; newHeight = height * newWidth / width; }
    else if (isweekman.SelectedValue == "1")
    { newWidth = 171; newHeight = height * newWidth / width; }
    else if (firstpageshow.SelectedValue == "1" && fenlei.SelectedValue == "3")
    { newWidth = 171; newHeight = height * newWidth / width; }
    else
    { newWidth = 62; newHeight = height * newWidth / width; }

    System.Drawing.Image thumb = img.GetThumbnailImage(newWidth, newHeight,
        new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

    string thumbPath = Server.MapPath("~/upload/small_" + newName + ext);
    thumb.Save(thumbPath);

    // 5. 釋放資源
    img.Dispose();
    thumb.Dispose();

    // 6. 回傳路徑供前端顯示
    pic = "upload/" + newName + ext;
    smallpic = "upload/small_" + newName + ext;
}

關鍵技術點

  • 等比例縮放:newHeight = height * newWidth / width 保持長寬比,避免變形。
  • GetThumbnailImage:內建高速縮略圖產生,適用 Web 縮圖品質需求;高品質列印建議改用 Graphics.DrawImage + InterpolationMode.HighQualityBicubic。
  • 資源釋放:Image 實作 IDisposable,務必 Dispose() 釋放 GDI+ 控制代碼,防止記憶體洩漏。
  • 檔名唯一性:年份天數 + 檔案大小極低機率重複;正式環境建議改用 Guid.NewGuid() 或 DateTime.Ticks。

安全性補強 (生產環境必做)

  1. 驗證 PostedFile.ContentType 為 image/ 開頭。
  2. 限制檔案大小 (如 < 5MB)。
  3. 儲存目錄設定 execute 權限移除,防止上傳腳本執行。
  4. 檔名不採用使用者原始檔名,避免路徑遍歷攻擊。

.NET Core / ASP.NET Core 遷移提示

System.Drawing.Common 僅支援 Windows;跨平台請改用 ImageSharp、SkiaSharp 或 Magick.NET 純 managed 影像庫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved