问题描述
我正在处理位图图像,其透明部分用洋红色着色(在某些语言中,可以将颜色设置为透明).我尝试在原始位图图像中透明洋红色的像素.
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.
我从SD卡加载位图:
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)
}
}
}
但是我希望变成透明的那些像素会转换为黑色.通过更改Alpha,我发现最终颜色从argb()
中提到的颜色(未提及Alpha)变为黑色.例如,Color.argb(0xff,0xff,0xff,0xff)
变为白色,Color.argb(0x80,0xff,0xff,0xff)
变为灰色,Color.argb(0x00,0xff,0xff,0xff)
变为黑色.
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.
是否可能没有alpha通道,我应该先设置/定义它?如果是,怎么办?
Could it be possible that there is no alpha channel and I should first set/define it? if yes, how?
根据Der Gol ... lum的评论,我修改了我的代码:
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);
}
}
}
但是结果大致相同.使用不同的PorterDuff
模式会导致整个位图透明或使目标像素变黑:
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:
有人有什么主意吗?
推荐答案
我终于可以找到问题所在.我的png图像没有Alpha通道,或者它们的Alpha通道未激活.我为解决此问题所做的就是添加:
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:
bitmap.setHasAlpha(true);
,它按我的预期工作.
and it works how I expected.
这篇关于无法使位图图像的像素透明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!