[VB]上傳圖片自動加入浮水印

上傳圖片加入浮水印

有時想在上傳圖片後自動加入浮水印圖案,如網站logo之類的,一方面防止盜圖,一方面節省使用繪圖工具修圖的時間,所以在程式中加入是最快最方便的一種選擇。

 

 

首先是先準備好你的Fileupload控制項的畫面跟確保能上傳成功,上傳的部分就不多加說明了,直接看浮水印加入的程式碼吧:

Sub join_img(ByRef str_Original As System.Drawing.Image, ByVal str_aterMark As String, ByVal img_path As String, ByVal de_name As String, Optional ByVal type As Integer = 0)

            '設定原有圖檔與浮水印圖檔的位置(此例為執行頁面同目錄下)
            'Dim original As String = Server.MapPath(img_path & str_Original)
            Dim watermark As String = Server.MapPath(img_path & str_aterMark)
            '建立兩個圖檔的Image以供稍後操作
            Try
                Using imageOriginal As System.Drawing.Image = str_Original, imageWatermark As System.Drawing.Image = System.Drawing.Image.FromFile(watermark)

                    '自原有圖片建立新的Image
                    Dim newImage As System.Drawing.Image = New Bitmap(imageOriginal)

                    '由newImage中取得Graphics物件
        Using newGraphic As Graphics = Graphics.FromImage(newImage)

                        '為了讓浮水印出現在圖片右上角, 故要算出浮水印繪製的座標
       Dim drawX As Int32 = (imageOriginal.Width - imageWatermark.Width) / 2
      Dim drawY As Int32 = (imageOriginal.Height - imageWatermark.Height) / 2
                      
                        '繪製浮水印
       newGraphic.DrawImageUnscaled(imageWatermark, New Point(drawX, drawY))

                        '儲存有浮水印的新圖片
        newImage.Save(Server.MapPath("~/upload/product/" & de_name), ImageFormat.Jpeg)
                    End Using
                End Using
            Catch ex As Exception
                Response.Write("<span style='color:red;'>" & ex.Message & "</span>")
            End Try
        End Sub

 

 

加入後在做好的上傳程式中叫用即可 :

Me.join_img(System.Drawing.Image.FromStream(upimgfile), "logo.png", "~/images/product/", file_name, 0)  '加入浮水印


 

 

想要有點變化的可以再加個Checkbox判斷是否要加入浮水印 :)
 

分享


站作網站設計工作室 SiteMak Studio
Shinyo Ho 
Founder / Developer
email:shinyo.her@gmail.com|web:www.sitemak.com.tw