I have an image loaded with Image
and ImageView
.
I want to make the background of the image, which is white, transparent to match with the background.
I have an image loaded with Image
and ImageView
.
I want to make the background of the image, which is white, transparent to match with the background.
See the resampling technique using a PixelWriter and WritableImage used in Reduce number of colors and get color of a single pixel. You can use the same technique and change the white pixels (rgb 255,255,255) to transparent (rgba 0,0,0,0).
You could also do this in an image editing program before you use the image in your application.
Here is a sample using the image from Easily Remove White Or Black Backgrounds with Blending Sliders in Photoshop.
A simple resampling implementation is shown below:
When the TOLERANCE_THRESHOLD is set to 0xFF, only pure white pixels will be changed to transparent, and you get the image as below. The white portion around the character is because some of the background is not exactly white but is slightly gray, so the resampling doesn't modify it's alpha value.
Decreasing the TOLERANCE_THRESHOLD to 0xCF produces an image like below, where some of the light gray background becomes transparent. Note that this outcome is not perfect as it there is still an aliased gray outline around the character and the white helmet of the character becomes transparent. You could modify the algorithm to be a bit more intelligent and act more like the lasso tool of an image drawing application, however that would probably get tricky and may still make mistakes without a human involved. If the simplistic programmatic routine below outlined above is not enough to correctly resample your image as you like, you will be best off setting up the transparency ahead of time in an image editing program (which is what I would recommend for most cases in any case).