Search code examples
androidbitmapandroid-canvasbitmapfactoryandroid-camera2

Android Image from camera saved with overlay


I've tried several different ways to get this to work but have come to a halt. I'm getting a photo from the camera and saving it with an overlay.

To combine the images, I have worked out how to do so with two bitmaps and a canvas like so:

   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();

The issue is I'm using camera2, which returns an Image. I haven't worked out a way to cast an Image to a Bitmap. I've tried saving the image and then reloading it using BitmapFactory, but frequently end up with OutOfMemory Exceptions.

Has anybody got a way they go around this?

UPDATE

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

I stumbled across this in another answer, but I am getting a Buffer not large enough for pixels exception, even when I have specified a buffer up to 8x larger than should have been necessary.


Solution

  • I worked out how to do this on my own with a lot of various SO answers for each step. It was a bit of trial and error, considering the number of bitmaps I need to manipulate in my app.

    A sample of the code to do so is as follows:

    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());
        }