Click here to Skip to main content
15,881,715 members
Articles / Programming Languages / C# 3.5
Tip/Trick

How to detect if an image is a transparent GIF

Rate me:
Please Sign up or sign in to vote.
3.40/5 (2 votes)
6 Jul 2012CPOL 16K   7   1
This is quite useful if you are building a crawler or need to download images from public sources. Transparent images can be easily discarded.

Introduction

I just ran into a problem where I needed to detect if a downloaded image (GIF) is completely transparent or not.  

Background 

This is quite useful if you are building a crawler or need to download images from public sources. Transparent images can be easily discarded.

Using the code 

The function IsTransparentPalette(..) can be used to detect if an image is 100% transparent. 

Copy the following functions to  your code and call them as follows: 

C#
System.Drawing.Image objImage = DownloadImage("https://www.google.com/images/srpr/logo3w.png");
C#
if (IsTransparentPalette(objImage.Palette)) {//your code....}     
C#
public bool IsTransparentPalette(System.Drawing.Imaging.ColorPalette palette)
{
    if (palette.Flags!= 1 )
        return false;

    int total_colors = palette.Entries.GetLength(0);
    for (int i = 0; i < total_colors - 1; i++)
    {
        if (palette.Entries[i].A != 0)
        {
            return false;
        }
    }
    return true;
}
public System.Drawing.Image DownloadImage(string url)
{
    System.Drawing.Image tmpImage = null;

    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        request.AllowWriteStreamBuffering = true;

        request.UserAgent = UserAgent;
        request.Accept = "GET HTTP/1.1";

        request.Timeout = 2000;

        System.Net.WebResponse webResponse = request.GetResponse();

        System.IO.Stream webStream = webResponse.GetResponseStream();

        if (webStream != null) tmpImage = System.Drawing.Image.FromStream(webStream);

        webResponse.Close();
        webResponse.Close();
    }
    catch (Exception exception)
    {
        return null;
    }

    return tmpImage;
} 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 3 Pin
charles henington12-Jul-12 14:59
charles henington12-Jul-12 14:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.