Trick to resize transparent images

written by Amr ElGarhy on Sunday, December 27 2009

I wanted to make a small image resize function in my asp.net website, and everything worked fine, but i faced a problem resizing transparent .png and .gif images.

After resizing done, i find that the output resized images transparent parts become white color and not transparent anymore.

This was my code:

Graphics objGraphics;

objGraphics = System.Drawing.Graphics.FromImage(imgFinal);
objGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; /* new way */
objGraphics.SmoothingMode = SmoothingMode.AntiAlias;
objGraphics.DrawImage(imgOriginal, 0, 0, iNewWidth, iNewHeight);
objGraphics.Dispose();

imgFinal.Save("filename");

 

And searched to find a solution for this problem with no hope for a complete easy solution.

 

And while trying to find a way, i remembered that i did a small resize tool “windows application” 4 years ago, i decided to try it and see the output, and i found after resize the image, the output is very nice and preserve transparent :).

I traced the code, and found the only difference is that in my windows application i was using the PictureBox control not the Graphics class.

I copies the code from there and put in my asp.net “sure needed to import System.Windows.Forms library in my asp.net to use the PictureBox control”.

 

And the Code became:

PictureBox pic = new PictureBox();
pic.Image = imgOriginal;
imgFinal = new System.Drawing.Bitmap(pic.Image, iTargetWidth, iTargetHeight);
imgFinal.Save("filename");

 

 

I believe that using Windows form control in asp.net is odd, but it solved my current problem, it may need some more testing for performance issues.

Digg It!  StumbleUpon  Reddit  Del.icio.us  NewsVine  Furl  BlinkList  Ma.gnolia  Technorati

Similar Posts

  1. Indexed pixel format problem in GDI+
  2. 10+ Ways for testing website browser compatibility
  3. Intro to ASP.Net Maker

Post a comment

Options:

Size

Colors