65.9K
CodeProject is changing. Read more.
Home

How to detect if an image is a transparent GIF

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.40/5 (2 votes)

Jul 6, 2012

CPOL
viewsIcon

16372

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: 

System.Drawing.Image objImage = DownloadImage("https://www.google.com/images/srpr/logo3w.png");
if (IsTransparentPalette(objImage.Palette)) {//your code....}     
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;
}