Trick to resize transparent images

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:

 

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:

 

 

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.

One thought on “Trick to resize transparent images

  1. I know it’s an old article.

    Best way is;

    Image src = Image.FromFile(srcPath);

    double ratio = 0.5;

    Image dest = src.GetThumbnailImage((int)(src.Width * ratio), (int)(src.Height * ratio), null, new IntPtr(0));

    dest.Save(destPath);

Comments are closed.