Wednesday 23 April 2008

Transparent GIFs in .Net hell!!

There is a very useful article here about creating transparent gifs in .net, but there are (I think) a couple of points missing, which I'll detail here in case it saves anyone wasting a day scratching their head like I have...

GDI+ Version
It would appear that there are differences between versions 1.0 (file version 5.x) and 1.1 (6.x) of Microsoft's GDI+, in the way that they encode a non-indexed bitmap (eg 32bppARGB) into an indexed format such as Format8bppIndexed.

The problem comes with the converted palette; on my development machine (gdiplus.dll version 6.x), I appeared to be getting a custom palette based on (maybe?) the colours in the converted image (image quantization).

On a Windows 2003 server, running gdiplus.dll 5.x, I would get the standard palette as per Bob Powell's article.

This could potentially cause headaches for you if (as I did) you released a web project to production and it didn't behave as it did on your dev machine...

There appears to be very little documentation on this change between gdi+ 1.0 and 1.1, but what links I found I've added below.

Altering GIF palette
When I tried to adapt Bob's algorithm to make my gif's background transparent, I ran into a problem. Sometimes the algorithm would work, sometimes it wouldn't. At this stage, the only conclusion I can draw is that you must remove any transparent colours from the palette before attempting to set a new transparent colour... i.e, don't do this (variation of Bob's code):

'copy all the entries from the old palette removing any transparency
Dim n As Integer = 0
Dim c As Color
For Each c In cp.Entries
If n = idxToMakeTransparent Then
ncp.Entries(n) = Color.FromArgb(0, c)
Else
ncp.Entries(n) = Color.FromArgb(255, c)
End If

n += 1
Next c

're-insert the palette
bm.Palette = ncp

I think that this doesn't work if one of the colours is already defined as transparent (as seems to be the default in old gdi+ (1.0). This is all pure speculation at this point!

Good luck with your hacking.

Links
http://www.xtremevbtalk.com/t92821.html
http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q319061
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/colorquant.asp

No comments: