Add Watermark Text on Uploaded Image in Asp.Net
(How to add Watermark Text to an image dynamically while uploading in ASP.NET) – Trong bài viết trước chúng tôi đã giới thiệu cách thêm Watermark vào ảnh bằng một hình ảnh được thiết lập mặc định. Với cách này, Watermark sẽ đẹp hơn do được sử dụng bằng hình ảnh tuy nhiên nó lại không chủ động cho người sử dụng trong việc thay đổi thông tin. Bài viết dưới đây sẽ hướng dẫn cho các bạn thêm một cách để add Watermark vào hình ảnh bằng Text. Với cách này người dùng hoàn toàn có thể chủ động hoàn toàn trong việc đưa thông tin Watermark vào ảnh.
- B1: Tạo Project trong Microsoft Visual Studio 2010
- B2: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
C# Code
<%@ Page
Title="Add
Watermark Text on Uploaded Image in Asp.Net" Language="C#"
MasterPageFile="~/Site.master"
AutoEventWireup="true"
CodeBehind="Default.aspx.cs"
Inherits="AddWatermarkTextOnUploaded._Default"
%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<table cellpadding="3"
cellspacing="5"
border="0"
width="50%">
<tr>
<td>
<div
class="panel
panel-default">
<div
class="panel-heading">
<asp:label id="lblHeader" runat="server" Text="Add Watermark Text on Uploaded Image in
Asp.Net"></asp:label>
</div>
<div
class="panel-body">
<table cellspacing="2"
cellpadding="3"
border="0"
width="100%">
<tr>
<td style="width:28%;">
<asp:label id="plWatermarkText"
runat="server"
Text="WatermarkText
(*)"></asp:label>
</td>
<td>
<asp:TextBox ID="txtWatermarkText"
CssClass="form-control"
runat="server"
Width="250px"></asp:TextBox>
<asp:RequiredFieldValidator
ID="valWatermarkText"
ValidationGroup="validate"
runat="server"
ControlToValidate="txtWatermarkText"
Display="dynamic" ErrorMessage="Enter Watermark Text"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:label id="plImageName"
runat="server"
Text="Image Name
(*)"></asp:label>
</td>
<td>
<asp:FileUpload ID="FileUpload"
runat="server"
Width="150px"
/><br />
<asp:CustomValidator id="valFile"
runat="server"
CssClass="NormalRed"
ValidationGroup="validate"
ErrorMessage="You
Must Upload A File" Display="Dynamic"></asp:CustomValidator>
<asp:CustomValidator id="valType"
runat="server"
CssClass="NormalRed"
ValidationGroup="validate"
Display="Dynamic"></asp:CustomValidator>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Image ID="imgPreview"
Visible="false"
runat="server"
/>
</td>
</tr>
<tr>
<td colspan="2">
<asp:label id="lblMessage"
runat="server"
Visible="false"></asp:label>
</td>
</tr>
</table>
</div>
<div
class="modal-footer">
<div class="btn-group">
<asp:LinkButton id="cmdUpload"
runat="server"
CssClass="btn
btn-small" OnClick="cmdUpload_Click" ValidationGroup="validate" Causesvalidation="true">
<i class="icon-upload"></i> <asp:label id="lblUpload" runat="server" Text="Upload"></asp:label>
</asp:LinkButton>
</div>
</div>
</div>
</td>
</tr>
</table>
</asp:Content>
VB.NET Code
<%@ Page
Title="Add
Watermark Text on Uploaded Image in Asp.Net" Language="vb"
MasterPageFile="~/Site.Master"
AutoEventWireup="false"
CodeBehind="Default.aspx.vb"
Inherits="AddWatermarkTextOnUploaded._Default"
%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<table cellpadding="3"
cellspacing="5"
border="0"
width="50%">
<tr>
<td>
<div
class="panel
panel-default">
<div
class="panel-heading">
<asp:label id="lblHeader" runat="server" Text="Add Watermark Text on Uploaded Image in
Asp.Net"></asp:label>
</div>
<div
class="panel-body">
<table cellspacing="2"
cellpadding="3"
border="0"
width="100%">
<tr>
<td style="width:28%;">
<asp:label id="plWatermarkText"
runat="server"
Text="WatermarkText
(*)"></asp:label>
</td>
<td>
<asp:TextBox ID="txtWatermarkText"
CssClass="form-control"
runat="server"
Width="250px"></asp:TextBox>
<asp:RequiredFieldValidator
ID="valWatermarkText"
runat="server"
ValidationGroup="validate"
ControlToValidate="txtWatermarkText"
Display="dynamic" ErrorMessage="Enter Watermark Text"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:label id="plImageName"
runat="server"
Text="Image Name
(*)"></asp:label>
</td>
<td>
<asp:FileUpload ID="FileUpload"
runat="server"
Width="150px"
/><br />
<asp:CustomValidator id="valFile"
runat="server"
CssClass="NormalRed"
ValidationGroup="validate"
ErrorMessage="You
Must Upload A File" Display="Dynamic"></asp:CustomValidator>
<asp:CustomValidator id="valType"
runat="server"
CssClass="NormalRed"
ValidationGroup="validate"
Display="Dynamic"></asp:CustomValidator>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Image ID="imgPreview"
Visible="false"
runat="server"
/>
</td>
</tr>
<tr>
<td colspan="2">
<asp:label id="lblMessage"
runat="server"
Visible="false"></asp:label>
</td>
</tr>
</table>
</div>
<div
class="modal-footer">
<div class="btn-group">
<asp:LinkButton id="cmdUpload"
runat="server"
CssClass="btn
btn-small" ValidationGroup="validate" Causesvalidation="true">
<i class="icon-upload"></i> <asp:label id="lblUpload" runat="server" Text="Upload"></asp:label>
</asp:LinkButton>
</div>
</div>
</div>
</td>
</tr>
</table>
</asp:Content>
- B3: Viết Code cho file Default.aspx
C# Code
//Visit http://www.laptrinhdotnet.com
for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.Web.UI;
using System.Web;
using System.Drawing;
using System.Web.UI.WebControls;
namespace AddWatermarkTextOnUploaded
{
public partial class _Default :
System.Web.UI.Page
{
#region
"Private Members"
private string
FilePath;
private string
FileFilter = "gif,jpg,jpeg,png";
#endregion
#region
"Private Methods"
protected string
UploadFile(FileUpload Upload)
{
string fileName = "";
string fileExtension = "";
SetFilePath();
System.Drawing.Image bmpUpload =
System.Drawing.Image.FromStream(Upload.PostedFile.InputStream);
fileExtension = Path.GetExtension(Upload.FileName).Replace(".", "");
fileName = Upload.FileName.Substring(Upload.FileName.LastIndexOf("\\\\") + 1);
fileName = fileName.Substring(0,
fileName.LastIndexOf(fileExtension)) + fileExtension;
FilePath = FilePath + fileName;
using (Graphics g
= Graphics.FromImage(bmpUpload))
{
int opacity = 128;
SolidBrush
brush = new SolidBrush(Color.FromArgb(opacity, Color.White));
Font font = new
Font("Arial",
16, FontStyle.Bold);
g.DrawString(txtWatermarkText.Text.Trim(), font, brush, new PointF(bmpUpload.Width
/ 15, bmpUpload.Height / 15));
bmpUpload.Save(Path.Combine(FilePath));
imgPreview.ImageUrl = ResolveUrl("~/Upload/")
+ fileName;
imgPreview.Visible = true;
}
return fileName;
}
private void
SetFilePath()
{
FilePath = MapPath("~/Upload/");
//Create Folder
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}
}
#endregion
#region
"Event Handles"
protected void
cmdUpload_Click(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
try
{
string
fileName = "";
if (!string.IsNullOrEmpty(FileUpload.PostedFile.FileName))
{
fileName =
UploadFile(FileUpload);
if (!string.IsNullOrEmpty(fileName))
{
lblMessage.Text = "Upload file Sucessfully";
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Visible
= true;
}
}
}
catch (Exception
ex)
{
lblMessage.Text = ex.Message;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Visible = true;
return;
}
}
}
protected void
valFile_ServerValidate(object source, ServerValidateEventArgs args)
{
if (FileUpload.PostedFile != null)
{
if (FileUpload.PostedFile.ContentLength
> 0)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
}
protected void
valType_ServerValidate(object source, ServerValidateEventArgs args)
{
if (FileUpload.PostedFile != null)
{
lblMessage.Visible = false;
if (FileUpload.PostedFile.ContentLength
> 0)
{
string[] arr =
FileUpload.PostedFile.FileName.Split(Convert.ToChar('.'));
string FileType = arr[arr.Length -
1].ToLower();
valType.ErrorMessage = "You must upload
a file that is either a gif, jpg, jpeg, png";
if (FileFilter.IndexOf(FileType) >
-1)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
else
{
args.IsValid = false;
}
}
}
#endregion
}
}
VB.NET Code
'Visit http://www.laptrinhdotnet.com
for more ASP.NET Tutorials
Imports System.IO
Imports System.Drawing
Namespace AddWatermarkTextOnUploaded
Public Class _Default
Inherits System.Web.UI.Page
#Region "Private
Members"
Private FilePath As String = ""
Private FileFilter As
String = "gif,jpg,jpeg,png"
#End Region
#Region "Private
Methods"
Protected Function
UploadFile(ByVal Upload As FileUpload) As String
Dim fileName As String = ""
Dim fileExtension As String = ""
SetFilePath()
Dim bmpUpload As Image = Image.FromStream(Upload.PostedFile.InputStream)
fileExtension = Replace(Path.GetExtension(Upload.FileName),
".", "")
fileName = Upload.FileName.Substring(Upload.FileName.LastIndexOf("\\") + 1)
fileName = fileName.Substring(0, fileName.LastIndexOf(fileExtension))
& fileExtension
FilePath = FilePath + fileName
Using g As Graphics = Graphics.FromImage(bmpUpload)
Dim opacity As
Integer = 128
Dim brush As
New SolidBrush(Color.FromArgb(opacity, Color.White))
Dim font As
New Font("Arial", 16, FontStyle.Bold)
g.DrawString(txtWatermarkText.Text.Trim, font, brush, New PointF(bmpUpload.Width
/ 15, bmpUpload.Height / 15))
bmpUpload.Save(Path.Combine(FilePath))
imgPreview.ImageUrl = ResolveUrl("~/Upload/")
& fileName
imgPreview.Visible = True
End Using
Return fileName
End Function
Private Sub
SetFilePath()
FilePath = MapPath("~/Upload/")
'Create Folder
If Not Directory.Exists(FilePath) Then
Directory.CreateDirectory(FilePath)
End If
End Sub
#End Region
#Region "Event
Handles"
Private Sub
cmdUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdUpload.Click
If Page.IsValid Then
Try
Dim fileName As
String = ""
If FileUpload.PostedFile.FileName
<> "" Then
fileName =
UploadFile(FileUpload)
If fileName <> ""
Then
lblMessage.Text = "Upload file Sucessfully"
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Visible
= True
End If
End If
Catch ex As
Exception
lblMessage.Text = ex.Message
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Visible = True
Exit Sub
End Try
End If
End Sub
Private Sub
valFile_ServerValidate(ByVal source As System.Object, ByVal args As
System.Web.UI.WebControls.ServerValidateEventArgs)
Handles valFile.ServerValidate
Try
If Not
FileUpload.PostedFile Is Nothing Then
If FileUpload.PostedFile.ContentLength
> 0 Then
args.IsValid = True
Return
End If
End If
args.IsValid = False
Catch exc As Exception
End Try
End Sub
Private Sub
valType_ServerValidate(ByVal source As System.Object, ByVal args As
System.Web.UI.WebControls.ServerValidateEventArgs)
Handles valType.ServerValidate
Try
If Not
(FileUpload.PostedFile Is Nothing) Then
lblMessage.Visible = False
If (FileUpload.PostedFile.ContentLength
> 0) Then
Dim arr As String() = FileUpload.PostedFile.FileName.Split(Convert.ToChar("."))
Dim fileType As String = arr(arr.Length - 1).ToLower()
valType.ErrorMessage = "You must upload a file that is either a gif, jpg,
jpeg, png"
If FileFilter <> ""
And Not InStr("," & FileFilter.ToLower, "," & fileType.ToLower) = 0 Then
args.IsValid = True
Return
Else
args.IsValid = False
End If
args.IsValid = False
End If
End If
Catch exc As Exception
End Try
End Sub
#End Region
End Class
Chúc các bạn thành công!
Quang Bình
No Comment to " Add Watermark Text on Uploaded Image in Asp.Net "