简体   繁体   中英

Open PNG-File, Edit Transparency (Alpha) and Save on Android with Java

I need to write an Android-Application that uses an existing PNG-File, changes it's transparency (let's say 50%) and overwrites that file.

I already tried to open the file as a bitmap, change the paint-alpha there and save it again, but it always looses it's transparency value.

MyBitmap.compress(Bitmap.CompressFormat.PNG, 100, myOutputStream);

I already read that changing the quality-value to 0 might help, but that also didn't do the trick:

MyBitmap.compress(Bitmap.CompressFormat.PNG, 100, myOutputStream);

I can prove that my transparency-funktion works but when I try to save that image as a PNG, the transparency is lost. This is how I make the bitmap transparent:

Paint AlphaPaint = new Paint();
AlphaPaint.setAlpha(Math.round(Opacity * 255));
Canvas canvas = new Canvas(MyImage);
canvas.drawBitmap(..., ..., ..., AlphaPaint);

Any help is appreciated! Performance does not matter in this case, if using a library is the easiest way, that's definately ok. Thanks in advance!

Try this way just iterate through all the pixels and then reduce the alpha by whatever percentage you want and set back the pixel to that bitmap.

int A=0, B=0, C=0, D=0, color=0, ncolor=0;

for(int i=0; i<width; i++)
{
    for(int j=0; j<height; j++)
    {
        color = bitmap.getPixel(i,j);
        A = (color >> 24) & 0xff; // Get Alpha
        R = (color >> 16) & 0xff;
        G = (color >>  8) & 0xff;
        B = (color) & 0xff;
        A = A/2; //REDUCE BY HALF SO DIVIDE BY 2(50%)
        ncolor = (A & 0xff) << 24 | (R & 0xff) << 16 | (G & 0xff) << 8 | (B & 0xff);
        bitmap.setPixel(i,j,ncolor);
    }
}

Its just a basic idea how you can solve your problem. Hope this helps you out.. Thank You.

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