I am working with bitmap images whose transparent parts are colored in magenta (in some languages it is possible to set a color as transparent). I try to transparent pixels which are in magenta in the original bitmap image.
I load the bitmap from SD-card:
Bitmap bitmap = BitmapFactory.decodeFile(myImagePath);
copy it to another bitmap to make it mutable:
Bitmap bitmap2 = bitmap.copy(Bitmap.Config.ARGB_8888,true);
Then scan it pixel by pixel to find pixels in magenta and try to change their transparency.
for(int x=0;x<bitmap2.getWidth();x++){
for(int y=0;y<bitmap2.getHeight();y++){
if(bitmap2.getPixel(x, y)==Color.rgb(0xff, 0x00, 0xff))
{
int alpha = 0x00;
bitmap2.setPixel(x, y , Color.argb(alpha,0xff,0xff,0xff)); // changing the transparency of pixel(x,y)
}
}
}
But those pixels which I expect to become transparent are converted to black. By changing the alpha, I found that the final color varies from the mentioned color in argb()
(without mentioning the alpha) to black. For instance, Color.argb(0xff,0xff,0xff,0xff)
gets white, Color.argb(0x80,0xff,0xff,0xff)
gets gray and Color.argb(0x00,0xff,0xff,0xff)
gets black.
I don't undrestand what's wrong.
Could it be possible that there is no alpha channel and I should first set/define it? if yes, how?
EDIT1:
According to the comment of Der Gol...lum I have modified my code:
Paint mPaint = new Paint();
mPaint.setAlpha(0);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
mPaint.setAntiAlias(true);
Bitmap bitmap = BitmapFactory.decodeFile(myBackImagePath).copy(Bitmap.Config.ARGB_8888 , true);
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(bitmap, 0, 0, mPaint);
if(bitmap.getPixel(0, 0)==Color.rgb(0xff, 0x00, 0xff))
{
for(int x=0;x<bitmap.getWidth();x++){
for(int y=0;y<bitmap.getHeight();y++){
if(bitmap.getPixel(x, y)==Color.rgb(0xff, 0x00, 0xff))
{
bitmap.setPixel(x, y,Color.TRANSPARENT);
}
}
}
But the result is more or less the same. Using different PorterDuff
Modes causes either transparency of the entire bitmap or make the targeted pixels black:
Would anybody have any idea?
I could finally find the problem. My png images had no alpha channel or maybe their alpha channel were not activated. what I did to solve this problem is to add:
and it works how I expected.