Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to detect if an image is a transparent GIF

0.00/5 (No votes)
6 Jul 2012 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: 

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;
} 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here