三種縮圖策略比較
| 策略 | 優點 | 缺點 |
| 固定寬高強制縮放 | 尺寸完全一致 | 圖片變形(胖/瘦) |
| 等比例縮放(長邊優先) | 不變形 | 短邊留白,無法填滿固定容器 |
| 固定比例裁剪(本文方案) | 不變形、填滿容器、尺寸固定 | 邊緣內容可能被切除 |
核心演算法
- 計算原圖長寬比
origRatio = OriginalWidth / OriginalHeight。
- 計算目標長寬比
targetRatio = newWidth / newHeight。
- 原圖較扁(
origRatio > targetRatio)→ 以目標高度縮放,再水平置中裁剪左右多餘。
- 原圖較高(
origRatio < targetRatio)→ 以目標寬度縮放,再垂直置中裁剪上下多餘。
完整函數代碼
<%
'=================================================
' 固定比例裁剪縮圖
' 失敗回傳 False,成功回傳 True
' srcPath - 來源圖片絕對路徑
' newWidth - 目標寬度
' newHeight - 目標高度
' destPath - 目標儲存絕對路徑
'=================================================
Function MakePic(srcPath, newWidth, newHeight, destPath)
On Error Resume Next
MakePic = False
Set Jpeg = Server.CreateObject("Persits.Jpeg")
If Err.Number <> 0 Then
Response.Write "錯誤:伺服器未安裝 AspJpeg 元件"
Response.End
End If
Jpeg.Quality = 100 ' 最高品質
Jpeg.Open srcPath
Jpeg.PreserveAspectRatio = True ' 先等比縮放
Dim origRatio, targetRatio
origRatio = Jpeg.OriginalWidth / Jpeg.OriginalHeight
targetRatio = newWidth / newHeight
If origRatio > targetRatio Then
' 太扁:鎖定高度,裁剪左右
Jpeg.Height = newHeight
Dim cropLeft, cropRight
cropLeft = CInt((Jpeg.Width - newWidth) / 2)
cropRight = cropLeft + newWidth
Jpeg.Crop cropLeft, 0, cropRight, newHeight
Else
' 太高:鎖定寬度,裁剪上下
Jpeg.Width = newWidth
Dim cropTop, cropBottom
cropTop = CInt((Jpeg.Height - newHeight) / 2)
cropBottom = cropTop + newHeight
Jpeg.Crop 0, cropTop, newWidth, cropBottom
End If
Jpeg.Save destPath
If Err.Number = 0 Then MakePic = True
Jpeg.Close
Set Jpeg = Nothing
End Function
%>
呼叫範例
<%
' 產生 300x200 縮圖
Dim src, dest, ok
src = Server.MapPath("/uploads/photo.jpg")
dest = Server.MapPath("/thumbs/photo_300x200.jpg")
ok = MakePic(src, 300, 200, dest)
If ok Then
Response.Write "縮圖產生成功:/thumbs/photo_300x200.jpg"
Else
Response.Write "縮圖產生失敗"
End If
%>
進階應用:批次處理上傳圖片
<%
' 上傳處理頁面片段
Dim upload, file, fileName, thumbName
Set upload = Server.CreateObject("Persits.Upload")
upload.Save Server.MapPath("/uploads")
For Each file In upload.Files
fileName = file.Path
thumbName = Replace(fileName, "\uploads\", "\thumbs\")
thumbName = Replace(thumbName, ".", "_300x200.")
If MakePic(fileName, 300, 200, thumbName) Then
' 記錄資料庫:原圖路徑、縮圖路徑
End If
Next
%>
安裝與授權提醒