locked
Watermarking Code works, but not if used in codebehind file? RRS feed

  • Question

  • User-1439843937 posted

    Puzzled why the same Sub Page_Load code will not work if used on the codebehind file. Current code works fine if used directly on the aspx page,  but as soon as i try placing the same code in a codebehind file the images will not show at all. Will post code sample if requested..

    The way the code is setup thumbnail page opens a new page that displays larger image with watermark. the watermark page only contains code that creates the watermark for the larger image page.

     

    Thanks inadvance for any suggestions

    1idesigned

    Sunday, November 1, 2009 5:51 PM

Answers

  • User-952121411 posted

    I think I have found the problem.  If you tried debugging the code you attempted to place in the page behind .vb file, I think you would find it does not even get ran.  The reason has to do with how you copied and pasted the signature of the 'Page_Load' Sub().  That signature works fine using script tags in the Page's source, but if you place it in the page behind code, you need to wire it up to an event unsing the VB.NET 'Handles' statement.

    So the following code in the page behind which currently does not work:

    Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

     

    ...needs to be changed to the following code which assigns a 'Handles' stament, telling .NET to run that code when the page is loaded:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    By the way, the easiest way to get the proper event handlers for page and control events is to use the (2) dropdowns at the top of the IDE showing the code in VS.NET.  So for Page_Load (which is typically auto generated and already exists) you could select '(Page Events)' from the dropdown on the left hand screen dropdown and 'Load' from the right-hand dropdown.  This would create the method signature if it did not exist, or jump to it, if it did not yet exist yet.

    Hope this helps! Smile
     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 5, 2009 4:23 PM
  • User-1439843937 posted

    That was the answer. Thank you for your time. I really appreciate it. 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, November 6, 2009 11:13 PM

All replies

  • User290944018 posted

    Could you post your code sample?




    Sunday, November 1, 2009 6:01 PM
  • User-1439843937 posted

    Here is the code.

    Code that works
    <Code>

    <%@ Import Namespace="System.Drawing.Imaging" %>
    <%@ Import Namespace="System.Drawing" %>
    <%@ Import Namespace="System.Drawing.Drawing2D" %>

    <script language=vbscript runat=server >
     
        Function ThumbnailCallback() As Boolean
            Return False
        End Function

        Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

            'Get the image name – yourimage.jpg – from the query String

            Dim imageURL As String = Request.QueryString("img")
            Dim imageHeight As Integer
            Dim Path As String = "Admin/IncomingPhotos/"

            'Set the thumbnail width in px – the width will be calculated later to keep the original ratio.
            Dim imageWidth As Integer = 800
            Dim CurrentimgHeight As Integer
            Dim CurrentimgWidth As Integer
           
            imageURL = Server.MapPath(Path) & imageURL
           
            Dim fullSizeImg As System.Drawing.Image
            fullSizeImg = System.Drawing.Image.FromFile(imageURL)
     
            CurrentimgHeight = fullSizeImg.Height
            CurrentimgWidth = fullSizeImg.Width
            imageHeight = CurrentimgHeight / CurrentimgWidth * imageWidth

            'This will only work for jpeg images

            Response.ContentType = "image/jpeg"
            If imageHeight > 0 And imageWidth > 0 Then
                Dim dummyCallBack As System.Drawing.Image.GetThumbnailImageAbort
                dummyCallBack = New System.Drawing.Image.GetThumbnailImageAbort(AddressOf ThumbnailCallback)

                Dim thumbNailImg As System.Drawing.Image
                thumbNailImg = fullSizeImg.GetThumbnailImage(imageWidth, imageHeight, dummyCallBack, IntPtr.Zero)
     
                Dim g As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(thumbNailImg)
      
                Dim StringSizeF As SizeF, DesiredWidth As Single, wmFont As Font, RequiredFontSize As Single, Ratio As Single
      
                Dim strWatermark As String = "WATERMARK"

                'Set the watermark font 
      
                wmFont = New Font("Verdana", 16, FontStyle.Bold)
                DesiredWidth = imageWidth * 0.8
     
                'use the MeasureString method to position the watermark in the centre of the image
     
                StringSizeF = g.MeasureString(strWatermark, wmFont)
                Ratio = StringSizeF.Width / wmFont.SizeInPoints
                RequiredFontSize = DesiredWidth / Ratio
                wmFont = New Font("Verdana", RequiredFontSize, FontStyle.Bold)

                'Sets the interpolation mode for a high quality image
      
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
                g.DrawImage(fullSizeImg, 0, 0, imageWidth, imageHeight)
                g.SmoothingMode = SmoothingMode.HighQuality
      
                Dim letterBrush As SolidBrush = New SolidBrush(Color.FromArgb(50, 255, 255, 255))
                Dim shadowBrush As SolidBrush = New SolidBrush(Color.FromArgb(50, 0, 0, 0))
     
                'Enter the watermark text
                g.DrawString("WATERMARK", wmFont, shadowBrush, 75, (imageHeight * 0.5) - 36)
                g.DrawString("WATERMARK", wmFont, letterBrush, 77, (imageHeight * 0.5) - 38)
      
                thumbNailImg.Save(Response.OutputStream, ImageFormat.Jpeg)

            Else
                fullSizeImg.Save(Response.OutputStream, ImageFormat.Jpeg)
                Response.Write(imageURL)

            End If
            'Important, dispose of the image  – otherwise the image file will be locked by the server for several minutes
            fullSizeImg.Dispose()

        End Sub

    </script>

    Code Behind

    Imports System.Drawing
    Imports System.Drawing.Imaging
    Imports System.Drawing.Drawing2D
    Imports System.IO

    Public Class WaterMarkImage
        Inherits System.Web.UI.Page

        Function ThumbnailCallback() As Boolean
            Return False
        End Function


        Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

            'Get the image name – yourimage.jpg – from the query String
            Dim imageURL As String = Request.QueryString("img")
            Dim imageHeight As Integer
            Dim Path As String = "Admin/IncomingPhotos/"

            'Set the thumbnail width in px – the width will be calculated later to keep the original ratio.
            Dim imageWidth As Integer = 800
            Dim CurrentimgHeight As Integer
            Dim CurrentimgWidth As Integer

            imageURL = Server.MapPath(Path) & imageURL

            Dim fullSizeImg As System.Drawing.Image
            fullSizeImg = System.Drawing.Image.FromFile(imageURL)
            CurrentimgHeight = fullSizeImg.Height
            CurrentimgWidth = fullSizeImg.Width
            imageHeight = CurrentimgHeight / CurrentimgWidth * imageWidth

            'This will only work for jpeg images
            Response.ContentType = "image/jpeg"
            If imageHeight > 0 And imageWidth > 0 Then
                Dim dummyCallBack As System.Drawing.Image.GetThumbnailImageAbort
                dummyCallBack = New System.Drawing.Image.GetThumbnailImageAbort(AddressOf ThumbnailCallback)

                Dim thumbNailImg As System.Drawing.Image
                thumbNailImg = fullSizeImg.GetThumbnailImage(imageWidth, imageHeight, dummyCallBack, IntPtr.Zero)

                Dim g As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(thumbNailImg)
                Dim StringSizeF As SizeF, DesiredWidth As Single, wmFont As Font, RequiredFontSize As Single, Ratio As Single
                Dim strWatermark As String = "WATERMARK"

                'Set the watermark font 
                wmFont = New Font("Verdana", 16, FontStyle.Bold)
                DesiredWidth = imageWidth * 0.8

                'use the MeasureString method to position the watermark in the centre of the image
                StringSizeF = g.MeasureString(strWatermark, wmFont)
                Ratio = StringSizeF.Width / wmFont.SizeInPoints
                RequiredFontSize = DesiredWidth / Ratio
                wmFont = New Font("Verdana", RequiredFontSize, FontStyle.Bold)

                'Sets the interpolation mode for a high quality image
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
                g.DrawImage(fullSizeImg, 0, 0, imageWidth, imageHeight)
                g.SmoothingMode = SmoothingMode.HighQuality

                Dim letterBrush As SolidBrush = New SolidBrush(Color.FromArgb(50, 255, 255, 255))
                Dim shadowBrush As SolidBrush = New SolidBrush(Color.FromArgb(50, 0, 0, 0))

                'Enter the watermark text
                g.DrawString("WATERMARK", wmFont, shadowBrush, 75, (imageHeight * 0.5) - 36)
                g.DrawString("WATERMARK", wmFont, letterBrush, 77, (imageHeight * 0.5) - 38)

                thumbNailImg.Save(Response.OutputStream, ImageFormat.Jpeg)

            Else
                fullSizeImg.Save(Response.OutputStream, ImageFormat.Jpeg)
                Response.Write(imageURL)

            End If
            'Important, dispose of the image  – otherwise the image file will be locked by the server for several minutes
            fullSizeImg.Dispose()

        End Sub

    End Class

    I call the watermark page using the following code, the watermark only works if i use the watermarked_thumbnail.aspx, same code placed in WaterMarkImage.aspx that is in the code behind will not work. It will not show any image.

                            <td rowspan="4" align="left" valign="middle" width="800px">
                                <asp:Image ID="fullSizeImg" runat="server" ImageUrl='<%# "watermarked_thumbnail.aspx?img=" & Eval("ImageFilePath") %>' Height="600px" Width="800px" ImageAlign="Middle" AlternateText='<%# "Title: " & Eval("Title") %>'
                                    ToolTip='<%# "Title "  & Eval("Title") %>' />
                            </td>

     

     Hope this helps

    Wednesday, November 4, 2009 10:51 PM
  • User-952121411 posted

    I think I have found the problem.  If you tried debugging the code you attempted to place in the page behind .vb file, I think you would find it does not even get ran.  The reason has to do with how you copied and pasted the signature of the 'Page_Load' Sub().  That signature works fine using script tags in the Page's source, but if you place it in the page behind code, you need to wire it up to an event unsing the VB.NET 'Handles' statement.

    So the following code in the page behind which currently does not work:

    Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

     

    ...needs to be changed to the following code which assigns a 'Handles' stament, telling .NET to run that code when the page is loaded:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    By the way, the easiest way to get the proper event handlers for page and control events is to use the (2) dropdowns at the top of the IDE showing the code in VS.NET.  So for Page_Load (which is typically auto generated and already exists) you could select '(Page Events)' from the dropdown on the left hand screen dropdown and 'Load' from the right-hand dropdown.  This would create the method signature if it did not exist, or jump to it, if it did not yet exist yet.

    Hope this helps! Smile
     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 5, 2009 4:23 PM
  • User-1439843937 posted

    That was the answer. Thank you for your time. I really appreciate it. 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, November 6, 2009 11:13 PM
  • User435502292 posted

    Hi i just read post that is talking about watermark code. My question is. Is that possible to write width

    Dim imageWidth as Integer = 640

    in percentage not in px, because i use fancybox and if i put 640 px width, when i open a small image (100px or smaller) in fancybox that resize to that number. Or is there a workaround somehow to show image in original size with watermak text on it.

    Thanks for any answers.


    Wednesday, January 20, 2010 1:32 PM
  • User-952121411 posted

    Just for future reference, if you have a new question regarding a solved post, you should start a new post, and make a reference to the old post if needed.  Otherwise, your question may not be viewed.

    To set a width or height in code by percentage, you can do the following:

            'Width is of type 'Unit', so it needs to be assigned directly to the controls width property
            'or to a variable of type 'System.Web.UI.WebControls.Unit'
            Me.TextBox1.Width = System.Web.UI.WebControls.Unit.Percentage(640)


    If for some reason, this does not answer your question, I recommend you start a new one with your question.  Thanks!  

    Wednesday, January 20, 2010 1:55 PM
  • User435502292 posted

    Firs of all thank you for your quick reply. Second I apoligize if I reply... in the future i will start a new post. If we start talk Iwould like to continue in this post if you agree.

    I'm not that good in aspx so that code you paste should I replace it with code that i posted or is there some other things to do? If you so kind I will paste entire code you just mark where must apply the percentage.


    Function ThumbnailCallback() as Boolean
        Return False
      End Function
    
    
       Sub Page_Load(sender as Object, e as EventArgs)
    
    'Get the image name – yourimage.jpg – from the query String
    
       Dim imageURL as String = Request.QueryString("img")
             Dim imageHeight as Integer 
    
    
    'Set the thumbnail width in px – the width will be calculated later to keep the original ratio.
            
    Dim imageWidth as Integer = 640 Dim CurrentimgHeight As Integer Dim CurrentimgWidth As Integer imageUrl = "E:\image\" & imageURL Dim fullSizeImg as System.Drawing.Image fullSizeImg = System.Drawing.Image.FromFile(imageUrl) CurrentimgHeight = fullSizeImg.Height CurrentimgWidth = fullSizeImg.Width imageHeight = CurrentimgHeight / CurrentimgWidth * imageWidth 'This will only work for jpeg images Response.ContentType = "image/jpeg" If imageHeight > 0 and imageWidth > 0 then Dim dummyCallBack as System.Drawing.Image.GetThumbNailImageAbort dummyCallBack = New _ System.Drawing.Image.GetThumbnailImageAbort(AddressOf ThumbnailCallback) Dim thumbNailImg as System.Drawing.Image thumbNailImg = fullSizeImg.GetThumbnailImage(imageWidth, imageHeight, _ dummyCallBack, IntPtr.Zero) Dim g As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(thumbNailImg) dim StringSizeF as SizeF, DesiredWidth as Single, wmFont as Font, RequiredFontSize as Single, Ratio as Single Dim strWatermark = "WATERMARK" 'Set the watermark font wmFont = New Font("Verdana", 14, FontStyle.Bold) DesiredWidth = imagewidth * .2 'use the MeasureString method to position the watermark in the centre of the image StringSizeF = g.MeasureString(strWatermark, wmFont) Ratio = StringSizeF.Width / wmFont.SizeInPoints RequiredFontSize = DesiredWidth / Ratio wmFont = New Font("Verdana", RequiredFontSize, FontStyle.Bold) 'Sets the interpolation mode for a high quality image g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic g.DrawImage(fullSizeImg, 0, 0, imagewidth, imageheight) g.SmoothingMode = SmoothingMode.HighQuality Dim letterBrush as SolidBrush = new SolidBrush(Color.FromArgb(50, 255, 255, 255)) Dim shadowBrush as SolidBrush = new SolidBrush(Color.FromArgb(50, 0, 0, 0)) 'Enter the watermark text g.DrawString("WATERMARK", wmFont, shadowBrush, 7, (imageHeight * .1) - 36) g.DrawString("WATERMARK", wmFont, letterBrush, 7, (imageHeight * .1) - 38) thumbNailImg.Save(Response.OutputStream, ImageFormat.jpeg) Else fullSizeImg.Save(Response.OutputStream, ImageFormat.jpeg) End If 'Important, dispose of the image – otherwise the image file will be locked by the server for several minutes fullSizeImg.Dispose() End Sub


    Thanks.

    Wednesday, January 20, 2010 4:34 PM