0

我已经尝试了几种不同的方法来让它工作,但已经停止了。我正在从相机中获取照片并使用叠加层保存它。

为了组合图像,我已经研究出如何使用两个位图和一个画布来做到这一点,如下所示:

   Bitmap combined = Bitmap.createBitmap(mImage.getWidth(), mImage.getHeight(), null);
   Canvas canvas = new Canvas(combined);

   canvas.drawBitmap(image, new Matrix(), null);
   canvas.drawBitmap(mOverlay, 0,0,null);

   output = new FileOutputStream(new File(mFile.getPath(), mFileName + "(overlay).jpg" ));
   output.write(bytes);
   output.close();

问题是我正在使用camera2,它返回一个图像。我还没有找到将图像转换为位图的方法。我尝试保存图像,然后使用 BitmapFactory 重新加载它,但经常以 OutOfMemory 异常告终。

有没有人有办法解决这个问题?

更新

    Bitmap image = Bitmap.createBitmap(mImage.getWidth(),mImage.getHeight(), Bitmap.Config.ARGB_8888);
    image.copyPixelsFromBuffer(mImage.getPlanes()[0].getBuffer().rewind());

我在另一个答案中偶然发现了这个问题,但我遇到了一个Buffer not large enough for pixels例外,即使我指定了一个比应有的缓冲区大 8 倍的缓冲区。

4

1 回答 1

1

我自己解决了这个问题,每个步骤都有很多不同的 SO 答案。考虑到我需要在我的应用程序中操作的位图数量,这是一个反复试验。

执行此操作的代码示例如下:

ByteBuffer buffer = capturedImage.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.remaining()];

try {

    Bitmap imageBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, new BitmapFactory.Options()).copy(Bitmap.Config.RGB_565, true);
    Bitmap combined = Bitmap.createBitmap(imageBitmap, 0, 0, imageBitmap.getWidth(), imageBitmap.getHeight());
    imageBitmap.recycle();

    //overlay needs to be scaled to image size
    Bitmap scaledBitmap = Bitmap.createScaledBitmap(mOverlay, imageBitmap.getWidth(), imageBitmap.getHeight(), false); 
    mOverlay.recycle();

    Canvas canvas = new Canvas(combined);
    canvas.drawBitmap(scaledBitmap, 0, 0, new Paint());

    output = new FileOutputStream(new File(path));
    combined.compress(Bitmap.CompressFormat.JPEG, 100, output);
    output.close();

    combined.recycle();

    } catch (Exception ex) {
        Log.d(TAG, "Unable to combine and save images. " + ex.getMessage());
    }
于 2016-01-21T23:39:16.147 回答