简体   繁体   中英

How can I set an image to have a transparent background in C# without using Bitmap.MakeTransparent()?

I want to set an image to have a transparent background, but I do not want to replace all pixels of a specific colour with transparency.

To be more specific, the image is a thumbnail image for a folder, obtained via IShellItemImageFactory.GetImage. This gives me a Bitmap, as displayed in Windows Explorer thumbnail view, but the background is solid white.

I can use Bitmap.MakeTransparent on it, and that will work in most cases, but in any cases where the thumbnail image contains white itself (for example, a folder that contains images, which include white colours).

Incidently, this is the first time in over 10 years as a developer that, after googling my question, I have not found an answer anywhere, and I've actually had to ask it myself. (I think that means I just levelled up! Yippee, I am now a level 2 developer...)

Use flood-fill algorithm to fill pixels of the same color from the OUTSIDE as you need it. It is something similar to magic wand in photoshop.

http://en.wikipedia.org/wiki/Flood_fill

What I would do is flood-fill with some obscure color (Magenta always does it for me), then replace that color with transparent (I don't know if flood filling with transparent pixels is feasible).

So what you're getting from IShellItemImageFactory.GetImage is a composite image that contains the original image on a white background? I suspect the white background is there if the image doesn't have the same aspect ratio as the thumbnail size. For example, if you ask for a 96x96 thumbnail of a 640x480 image, there's going to be some white space at top and bottom.

If that's the case, you have a problem. You can't differentiate between white pixels that are contained in the image, and white pixels that are added by GetImage .

There are a few things you could do. You could load the image and resize it yourself. That's probably the easiest. You'd want to maintain your own thumbnail cache then.

Or you could examine the image returned by GetImage to look for white space on the sides. Basically, if every pixel on a row (or column) is white, then make that row (or column) transparent. It's a little more complicated than that ( the NBA logo , for example). But that's essentially what you'd want to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM