Last post Aug 15, 2011 10:18 PM by email@example.com
Jul 04, 2011 12:11 AM|sking|LINK
I have a trasparent gif and I'm resizing it with the following code which is turning the file into a black mess.
Size NewSize = new Size();
NewSize.Width = width;
NewSize.Height = height;
System.Drawing.Image smallergif = resizeImage(System.Drawing.Image.FromFile(@Server.MapPath("~/images/unavailable.gif")), NewSize);
smallergif.Save(@Server.MapPath("~/users/" + path + "/") + "unavailabler.gif", ImageFormat.Gif);
Bitmap b = new Bitmap(size.Width, size.Height);
Graphics g = Graphics.FromImage((System.Drawing.Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(imgToResize, 0, 0, size.Width, size.Height);
How do I tell it to preserve the transparency?
Aug 15, 2011 10:18 PMfirstname.lastname@example.org|LINK
You could try smallergif.MakeTransparent(), but that will only work for certain GIF images, not all of them.
The problem is that Windows has the world's buggiest GIF encoder.
To get a decent result, you need an octree quantizer with certain bugfixes applied to maintain the transparency. The only such code I know of is the
PrettyGifs plugin for
ImageResizing.net. There are other octree quantizers floating around, but they don't work on 64-bit windows and don't preserve transparency properly or support dithering.
Your new code using the library and plugin would be:
ResizeSettings s = new ResizeSettings();
s.MaxWidth = width;
s.MaxHeight = height;
ImageBuilder.Current.Build("~/images/unavailable.gif","~/users/" + path + "/unavailable.gif",s);
Viola, transparency preserved, great GIF quality, less code, and no memory leaks (see the image resizing pitfalls link in my signature).