Make Thumbnail - Transparent Gif problem - Black Background

Posted on 2005-05-12
Medium Priority
Last Modified: 2010-05-18

I have the following code to create thumbnail images on the fly. It works fine with .jpg, however when a .gif is passed in as the image the background of the image
turns black.

I understand there is a problem with keeping the transparency of gif images within .net
I would be happy if the background colour was just white.

Any Ideas?

     Public fileName As String
    Public imageWidth As Integer
    Public imageHeight As Integer

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here

        'get filename, width and height
        fileName = Request.QueryString("file")
        imageWidth = Request.QueryString("w")
        imageHeight = Request.QueryString("h")

        'imageWidth = 250
        'imageHeight = 400

        If imageWidth = Nothing Then
            imageWidth = 250
            imageWidth = imageWidth
        End If

        If imageHeight = Nothing Then
            imageHeight = 400
            imageHeight = imageHeight
        End If


    End Sub

    Function ThumbnailCallback() As Boolean
        Return False
    End Function

    Function imageResize()

        Dim fullSizeImg, thumbNailImg As System.Drawing.Image

        'Read in the image filename to create a thumbnail of
        Dim imageUrl As String = fileName

        'Read in the width and height
        'Dim imageHeight As Integer = "200" 'Request.QueryString("h")
        'Dim imageWidth As Integer = "200" 'Request.QueryString("w")

        'Make sure that the image URL doesn't contain any /'s or \'s
        If imageUrl.IndexOf("/") >= 0 Or imageUrl.IndexOf("\") >= 0 Then
            'We found a / or \
        End If

        'Add on the appropriate directory
        imageUrl = "media/" & imageUrl
        fullSizeImg = System.Drawing.Image.FromFile(Server.MapPath(imageUrl))

        Dim maxWidth, MaxHeight As Integer
        ' Get width using QueryString.
        If imageWidth = Nothing Then
            maxWidth = fullSizeImg.Width
        ElseIf imageWidth = 0 Then
            maxWidth = 100
            maxWidth = imageWidth
        End If

        ' Get height using QueryString.
        If imageHeight = Nothing Then
            MaxHeight = fullSizeImg.Height
        ElseIf imageHeight = 0 Then
            MaxHeight = 100
            MaxHeight = imageHeight
        End If

        Dim imgHeight, imgWidth As Integer
            fullSizeImg = fullSizeImg.FromFile(Server.MapPath(imageUrl))
            imgHeight = fullSizeImg.Height
            imgWidth = fullSizeImg.Width

            If imgWidth > maxWidth Or imgHeight > MaxHeight Then
                'Determine what dimension is off by more
                Dim deltaWidth As Integer = imgWidth - maxWidth
                Dim deltaHeight As Integer = imgHeight - MaxHeight
                Dim scaleFactor As Double

                If deltaHeight > deltaWidth Then
                    'Scale by the height
                    scaleFactor = MaxHeight / imgHeight
                    'Scale by the Width
                    scaleFactor = maxWidth / imgWidth
                End If

                imgWidth *= scaleFactor
                imgHeight *= scaleFactor
            End If

            fullSizeImg = fullSizeImg.FromFile(Server.MapPath("\ssm\images\ac_image\error.gif"))
        End Try

        'Do we need to create a thumbnail?
        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)

            thumbNailImg = fullSizeImg.GetThumbnailImage(imgWidth, imgHeight, dummyCallBack, IntPtr.Zero)

            ' send the resized image to the viewer  
            thumbNailImg.Save(Response.OutputStream, Imaging.ImageFormat.Jpeg) ' output to the user
            fullSizeImg.Save(Response.OutputStream, Imaging.ImageFormat.Jpeg)
        End If

        'Disposing the objects.

    End Function
Question by:leekey
  • 4
  • 3
LVL 11

Expert Comment

by:Ramesh Srinivas
ID: 13985494
Here is a CreateThumbnail function that clears up GIF images and sets background to white:

Public Shared Function CreateThumbnail(ByVal lcFilename As MemoryStream, ByVal lnWidth As Integer, ByVal lnHeight As Integer) As Bitmap
        Dim bmpOut As System.Drawing.Bitmap = Nothing
            Dim loBMP As New Bitmap(lcFilename)
            Dim loFormat As ImageFormat = loBMP.RawFormat
            Dim lnRatio As Decimal
            Dim lnNewWidth As Integer = 0
            Dim lnNewHeight As Integer = 0

            '*** If the image is smaller than a thumbnail just return it
            If loBMP.Width < lnWidth And loBMP.Height < lnHeight Then
                Return loBMP
            End If

            If loBMP.Width > loBMP.Height Then
                lnRatio = CDec(lnWidth) / loBMP.Width
                lnNewWidth = lnWidth

                Dim lnTemp As Decimal = loBMP.Height * lnRatio
                lnNewHeight = CInt(lnTemp)
                lnRatio = CDec(lnHeight) / loBMP.Height
                lnNewHeight = lnHeight

                Dim lnTemp As Decimal = loBMP.Width * lnRatio
                lnNewWidth = CInt(lnTemp)
            End If

            ' System.Drawing.Image imgOut =
            '      loBMP.GetThumbnailImage(lnNewWidth,lnNewHeight,
            '                              null,IntPtr.Zero);

            ' *** This code creates cleaner (though bigger) thumbnails and properly
            ' *** and handles GIF files better by generating a white background for
            ' *** transparent images (as opposed to black)
            bmpOut = New Bitmap(lnNewWidth, lnNewHeight)

            Dim g As Graphics = Graphics.FromImage(bmpOut)
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
            g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight)
            g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight)

            Return Nothing
        End Try

        Return bmpOut
    End Function 'CreateThumbnail

Author Comment

ID: 13987133

Thanks for the above.

I'm trying to set this function up. However on the line below:
Public Shared Function CreateThumbnail(ByVal lcFilename As MemoryStream, ByVal lnWidth As Integer, ByVal lnHeight As Integer) As Bitmap

My visual studio is saying "MemoryStream" isn't defined.
I'm a little new to .net

Any Ideas?
LVL 11

Expert Comment

by:Ramesh Srinivas
ID: 13987333
Import the System.IO namespace.
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Author Comment

ID: 13987374
OK great... done that.

This is how I'm calling the function.
But its saying (value of type "string" cannot be converted to "system.io.memorystream")

Sorry to keep coming back on this. I'm only used to basic .net functionaility....... Although I'll bet you'll say this is basic now!
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here

        'get filename, width and height
        fileName = Request.QueryString("file")
        imageWidth = Request.QueryString("w")
        imageHeight = Request.QueryString("h")

        CreateThumbnail(fileName, imageWidth, imageHeight)

    End Sub
LVL 11

Expert Comment

by:Ramesh Srinivas
ID: 13987438
What kind of path are you passing? Is it a URL??

Author Comment

ID: 13987476
yes.. This file is called MakeThumbnail.aspx

so I'm calling this page from others something like:

LVL 11

Accepted Solution

Ramesh Srinivas earned 2000 total points
ID: 13987676
I use an httpwebrequest to retrieve the image.

Here is how I get the image.

       Dim Path
            Path = New MemoryStream(GetImageFromURL(FILENAME))
        Catch er As Exception
            Path = New MemoryStream(GetImageFromURL("http://www.domain.com/NotAvailable.gif"))
        End Try
        Dim bmp As Bitmap = CreateThumbnail(Path, Size, Size)

        Response.ContentType = "image/jpeg"
        bmp.Save(Response.OutputStream, ImageFormat.Gif)
    End Sub

The httpwebrequest function to retrieve the image is:

Function GetImageFromURL(ByVal url As String) As Byte()
        Dim wr As HttpWebRequest = _
           DirectCast(WebRequest.Create(url), HttpWebRequest)
        Dim wresponse As HttpWebResponse = _
           DirectCast(wr.GetResponse, HttpWebResponse)
        Dim responseStream As Stream = wresponse.GetResponseStream
        Dim br As BinaryReader = New BinaryReader(responseStream)
        Dim bytesize As Long = wresponse.ContentLength
        Return br.ReadBytes(bytesize)
    End Function

This is a sub to handle error:

Private Sub ErrorResult()
        Response.StatusCode = 404
    End Sub 'ErrorResult

Then finally the CreateThumbnail function i have posted already.


Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses the ASP.NET AJAX ModalPopupExtender control. In this article we will show how to use the ModalPopupExtender control, how to display/show/call the ASP.NET AJAX ModalPopupExtender control from javascript, how to show/display/cal…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
Suggested Courses
Course of the Month15 days, 7 hours left to enroll

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question