在android中将图像转换为透明图像

时间:2015-10-25 03:10:19

标签: android bitmap android-bitmap

我需要将图像背景转换为透明图像,并将该图像保存在外部存储器中。下面是我厌倦的代码,但图像变为黑色背景,而不是透明。

这个指定pix [index] = Color.TRANSPARENT是否正确?

public Bitmap createTransparentBitmapFromBitmap( int replaceThisColor)            {

    try {
         // furniture1.JPG is the image to be converted. 
        InputStream is = getAssets().open("furniture1.JPG");
        Bitmap bitmap = BitmapFactory.decodeStream(is);

        if (bitmap != null) {
            int picw = bitmap.getWidth();
            int pich = bitmap.getHeight();
            int[] pix = new int[picw * pich];
            bitmap.getPixels(pix, 0, picw, 0, 0, picw, pich);

            for (int y = 0; y < pich; y++) {
                // from left to right
                for (int x = 0; x < picw; x++) {
                    int index = y * picw + x;
                    int r = (pix[index] >> 16) & 0xff;
                    int g = (pix[index] >> 8) & 0xff;
                    int b = pix[index] & 0xff;

                    if (pix[index] == replaceThisColor) {
                        pix[index] = Color.TRANSPARENT;
                    } else {
                        break;
                    }
                }

                // from right to left
                for (int x = picw - 1; x >= 0; x--) {
                    int index = y * picw + x;
                    int r = (pix[index] >> 16) & 0xff;
                    int g = (pix[index] >> 8) & 0xff;
                    int b = pix[index] & 0xff;

                    if (pix[index] == replaceThisColor) {
                        pix[index] = Color.TRANSPARENT;
                    } else {
                        break;
                    }
                }
            }


            Bitmap bm = Bitmap.createBitmap(pix, picw, pich,Bitmap.Config.ARGB_8888);
            Log.i("DATABASE", "mutable: "+bm.isMutable());

            is.close();
            return bm;
        }
        return null;
    }catch(Exception ex) {
        Log.i("DATABASE", "Problem updating picture", ex);
    }
    return null;
   }


// Creates an transparent image and save to SD card.
public void createTransparent() {

    // Replace WHITE color to TRANSPARENT color
    Bitmap bm = createTransparentBitmapFromBitmap(Color.WHITE);

    //Save the converted image to SD card
    boolean externalMounted= isExternalStorageWritable();
    File myDir=null;
    if(externalMounted)
    {
        String root = Environment.getExternalStorageDirectory().toString();
        myDir = new File(root + "/VirtualHome/Ikea","aaa1.jpeg");
        OutputStream os;
        try {
            os = new FileOutputStream(myDir);
            bm.compress(Bitmap.CompressFormat.JPEG, 100, os);
            os.flush();
            os.close();
        }catch(IOException ex) {
            Log.i("DATABASE", "Problem updating picture", ex);
            }

    }

}

0 个答案:

没有答案
相关问题