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

前提是你 提交于 2020-01-24 07:04:31

问题


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...)


回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/8458688/how-can-i-set-an-image-to-have-a-transparent-background-in-c-sharp-without-using

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!