Android合并两张图片

标签 android image merge android-canvas

我想合并两张图片,然后保存在Android SDCard上。一张来自相机,一张来自resources文件夹。问题是我收到此错误:由:java.lang.IllegalStateException:传递给 Canvas 构造函数的不可变位图引起。谢谢。

        Bitmap bottomImage = BitmapFactory.decodeResource(getResources(),R.drawable.blink);
        Bitmap topImage = (Bitmap) data.getExtras().get("data");  

        // As described by Steve Pomeroy in a previous comment, 
        // use the canvas to combine them.
        // Start with the first in the constructor..
        Canvas comboImage = new Canvas(bottomImage);
        // Then draw the second on top of that
        comboImage.drawBitmap(topImage, 0f, 0f, null);

        // bottomImage is now a composite of the two. 

        // To write the file out to the SDCard:
        OutputStream os = null;

        try {
            os = new FileOutputStream("/sdcard/DCIM/Camera/" + "myNewFileName.png");
            bottomImage.compress(CompressFormat.PNG, 50, os);

            //Bitmap image.compress(CompressFormat.PNG, 50, os);
        } catch(IOException e) {
            Log.v("error saving","error saving");
            e.printStackTrace();
        }

通过简单地进行此更改设法修复它:

        int w = bottomImage.getWidth();
        int h = bottomImage.getHeight(); 
        Bitmap new_image = Bitmap.createBitmap(w, h ,bottomImage.getConfig());

现在的问题是它不保存图像。你知道为什么吗?

最佳答案

This会帮助你 =)


编辑:(从链接嵌入答案)

返回可变位图的唯一静态“构造函数”是:

(Class: Bitmap) public static Bitmap createBitmap(int width, int height, boolean hasAlpha)
Returns: a mutable bitmap with the specified width and height.

  • 因此您可以使用 getPixels/setPixels 或像这样:

    Bitmap bitmapResult = bm.createBitmap(widthOfOld, heightOfOld, hasAlpha);
    Canvas c = new Canvas();
    c.setDevice(bitmapResult); // drawXY will result on that Bitmap
    c.drawBitmap(bitmapOld, left, top, paint);
    
  • 如何从 Bitmap 获取 drawable:通过使用扩展 Drawable 的 BitmapDrawable-Subclass,如下所示:

    Bitmap myBitmap = BitmapFactory.decode(path);
    Drawable bd = new BitmapDrawable(myBitmap);
    

关于Android合并两张图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6944061/

相关文章:

wpf - WPF图像的持续(快速)更新

java - 将图像添加到 Java Applet

javascript - 如何使水平长的图像也适合幻灯片放映?

c++ - 在 C++ 中通过引用传递未知大小的数组

javascript - 在 JavaScript 中如何将两个对象合并到同一个属性中?

java - 毕加索。第二次尝试时加载的图像

java - Activity A 调用 B,B 调用 C,需要 C 将数据发送回 A

java - System.setProperty 的范围

即使获得适当的权限,Android HTTP 连接仍被拒绝错误

python - 使用外部合并在 python 中合并两个 Pandas 数据帧不识别相同的值