合并两个位图图像(并排)

时间:2011-02-01 14:06:29

标签: android

任何人都可以帮助将两个位图图像组合成单个位图

在android中(并排)。

谢谢, Yuvaraj

3 个答案:

答案 0 :(得分:63)

您可以使用Canvas - 查看此文章:

http://www.jondev.net/articles/Combining_2_Images_in_Android_using_Canvas

更新了并排执行的代码:

public Bitmap combineImages(Bitmap c, Bitmap s) { // can add a 3rd parameter 'String loc' if you want to save the new image - left some code to do that at the bottom 
    Bitmap cs = null; 

    int width, height = 0; 

    if(c.getWidth() > s.getWidth()) { 
      width = c.getWidth() + s.getWidth(); 
      height = c.getHeight(); 
    } else { 
      width = s.getWidth() + s.getWidth(); 
      height = c.getHeight(); 
    } 

    cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 

    Canvas comboImage = new Canvas(cs); 

    comboImage.drawBitmap(c, 0f, 0f, null); 
    comboImage.drawBitmap(s, c.getWidth(), 0f, null); 

    // this is an extra bit I added, just incase you want to save the new image somewhere and then return the location 
    /*String tmpImg = String.valueOf(System.currentTimeMillis()) + ".png"; 

    OutputStream os = null; 
    try { 
      os = new FileOutputStream(loc + tmpImg); 
      cs.compress(CompressFormat.PNG, 100, os); 
    } catch(IOException e) { 
      Log.e("combineImages", "problem combining images", e); 
    }*/ 

    return cs; 
  } 

答案 1 :(得分:0)

选择的答案非常出色。 如果你想用位图的数组列表做并且并排看下面:

private Bitmap combineImageIntoOneFlexWidth(ArrayList<Bitmap> bitmap) {
        int w = 0, h = 0;
        for (int i = 0; i < bitmap.size(); i++) {
            if (i < bitmap.size() - 1) {
                h = bitmap.get(i).getHeight() > bitmap.get(i + 1).getHeight() ? bitmap.get(i).getHeight() : bitmap.get(i + 1).getHeight();
            }
            w += bitmap.get(i).getWidth();
        }

        Bitmap temp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(temp);
        int top = 0;
        for (int i = 0; i < bitmap.size(); i++) {
            Log.e("HTML", "Combine: " + i + "/" + bitmap.size() + 1);

            top = (i == 0 ? 0 : top + bitmap.get(i).getWidth());
            //attributes 1:bitmap,2:width that starts drawing,3:height that starts drawing
            canvas.drawBitmap(bitmap.get(i), top, 0f, null);
        }
        return temp;
    }

答案 2 :(得分:0)

我最终将xil3的答案修改为kotlin扩展功能,也许对某人有用。就我而言,我希望图像垂直堆叠

fun Bitmap?.combine(b: Bitmap?): Bitmap? =
when {
    b == null || this == null -> {
        this ?: b
    } else -> {
        val cs = Bitmap.createBitmap(
            max(this.width, b.width),
            this.height + b.height,
            Bitmap.Config.ARGB_8888
        )
        val canvas = Canvas(cs)
        canvas.drawBitmap(this, 0f, 0f, null)
        canvas.drawBitmap(b, 0f, this.height.toFloat(), null)
        cs
    }
}