合并两个位图

时间:2014-06-05 14:00:16

标签: android bitmap merge transparent

我喜欢在我的应用程序中合并两个相同大小的位图。 第一个Bitmap有一个" hud"主要是黑色背景。 第二个位图是一个人的图片。 我喜欢把#34; hud"在第二张照片上。

现在我的问题:我应该首先使第一个图像的黑色像素透明然后以某种方式组合这些图片,还是有一种算法会忽略第一张图片的黑色像素并获取第二张图片的像素? / p>

3 个答案:

答案 0 :(得分:1)

我找到了一个有效的解决方案:

public Bitmap createTransparentBitmapFromBitmap(Bitmap bitmap,
        int replaceThisColor) {
    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++) {
            for (int x = 0; x < picw; x++) {
                int index = y * picw + x;

                if (pix[index] == replaceThisColor) {
                    pix[index] = Color.TRANSPARENT;
                }
            }
        }
        Bitmap bm = Bitmap.createBitmap(pix, picw, pich,
                Bitmap.Config.ARGB_8888);
        return bm;
    }
    return null;
}

将此透明位图保存为png:

public void savePicture(Bitmap b1, String description, int instrCounter) {
    String path = Environment.getExternalStorageDirectory().toString()
            + "/BrushGuide";
    FileOutputStream out = null;
    try {
        File file = new File(path, description + instrCounter + ".PNG");
        out = new FileOutputStream(file);
        b1.compress(Bitmap.CompressFormat.PNG, 100, out);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            out.close();
        } catch (Throwable ignore) {
        }
    }

}

将此png图片与另一张保存在SD卡上的图片合并:

public Bitmap mergePictures() {
    Bitmap bitmap = null;
    try {

        bitmap = Bitmap.createBitmap(1100, 650, Config.ARGB_8888);
        Canvas c = new Canvas(bitmap);

        Drawable drawable1 = new BitmapDrawable(BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()
           .toString() + "/myfolder/photo.png"));
        Drawable drawable2 = new BitmapDrawable(BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()
           .toString() + "/myfolder/hud.png"));

        drawable1.setBounds(0, 0, 1100, 650);
        drawable2.setBounds(0, 0, 1100, 650);
        drawable1.draw(c);
        drawable2.draw(c);

    } catch (Exception e) {
    }
    return bitmap;

}

答案 1 :(得分:0)

透明度是要走的路。 HUD中的所有内容都是零alpha通道,您希望它在HUD下方显示底层图片。只有HUD中显示某些内容的像素具有非零alpha值。这样,当您将两个图像组合在一起时,您不需要任何像素逻辑 - 只需添加像素

答案 2 :(得分:0)

hud需要透明的背景。之后,您可以将两个位图与LayerList组合在一起。在res / drawable文件夹中创建一个xml文件并将其放入:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <bitmap android:src="@drawable/person" />
    </item>

    <item>
        <bitmap android:src="@drawable/hud" />
    </item>

</layer-list>

你可以像这样引用组合的drawable:R.drawable.name_of_xml_file

相关问题