C# 版完整實作 (.aspx 內嵌程式碼)
<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) ImgPreview.Visible = false;
}
void GetThumbnail(int width, int height, string waterMark, int left, int top)
{
string fileName = Path.GetFileName(uploadFile.PostedFile.FileName);
string savePath = Server.MapPath("~/Uploads/" + fileName);
string thumbPath = savePath + ".jpg";
uploadFile.PostedFile.SaveAs(savePath);
using (Image src = Image.FromFile(savePath))
using (Image thumb = src.GetThumbnailImage(width, height, () => false, IntPtr.Zero))
using (Bitmap bmp = new Bitmap(thumb))
using (Graphics g = Graphics.FromImage(bmp))
{
g.DrawString(waterMark, new Font("Courier New", 14), Brushes.Red, left, top);
bmp.Save(thumbPath, ImageFormat.Jpeg);
}
ImgPreview.ImageUrl = "~/Uploads/" + fileName + ".jpg";
ImgPreview.Visible = true;
}
protected void btnUpload_Click(object sender, EventArgs e)
{
if (uploadFile.PostedFile.ContentLength == 0)
{
lblErr.Text = "請選擇檔案";
return;
}
string fileName = Path.GetFileName(uploadFile.PostedFile.FileName);
string savePath = Server.MapPath("~/Uploads/" + fileName);
if (File.Exists(savePath))
{
lblErr.Text = "同名檔案已存在";
return;
}
int w = int.Parse(txtWidth.Text);
int h = int.Parse(txtHeight.Text);
int l = int.Parse(txtLeft.Text);
int t = int.Parse(txtRight.Text);
GetThumbnail(w, h, txtAddInfo.Text, l, t);
}
</script>
<html>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<asp:FileUpload ID="uploadFile" runat="server" />
<asp:Label ID="lblErr" runat="server" ForeColor="Red" /><br />
寬:<asp:TextBox ID="txtWidth" runat="server" Text="100" Width="40px" />
高:<asp:TextBox ID="txtHeight" runat="server" Text="150" Width="40px" /><br />
浮水印:<asp:TextBox ID="txtAddInfo" runat="server" Text="AspxBoy.Com" /><br />
位置 X:<asp:TextBox ID="txtLeft" runat="server" Text="10" Width="40px" />
Y:<asp:TextBox ID="txtRight" runat="server" Text="135" Width="40px" /><br />
<asp:Button ID="btnUpload" runat="server" Text="上傳並產生縮圖" OnClick="btnUpload_Click" /><br />
<asp:Image ID="ImgPreview" runat="server" Visible="false" />
</form>
</body>
</html>
VB.NET 版關鍵邏輯 (同上功能)
Dim img As Image = Image.FromFile(srcPath)
Dim newW, newH As Integer
If img.Width > img.Height Then
newW = 250
newH = img.Height * 250 / img.Width
Else
newH = 250
newW = img.Width * 250 / img.Height
End If
Dim thumb = img.GetThumbnailImage(newW, newH, Nothing, IntPtr.Zero)
thumb.Save(thumbPath, Imaging.ImageFormat.Jpeg)
img.Dispose()
關鍵點提醒
- 使用
GetThumbnailImage 快速產生縮圖,但品質較 Graphics.DrawImage 低;高品質需求請改用 Graphics.InterpolationMode.HighQualityBicubic。
- 儲存路徑需具備寫入權限。
- 上傳大檔案請調整
maxRequestLength (web.config)。
- 記得
Dispose() 釋放非受控資源。