1

I've used the sample code from Google to implement a custom camera using Camera2 API. I want to display the captured image in the next activity.

Camera2Basic sample code

However, I'm unable to safely exit the Camera2BasicFragment and start the next activity to display the captured image.

This is the code where I'm trying to start the next activity:

private final ImageReader.OnImageAvailableListener mOnImageAvailableListener
            = new ImageReader.OnImageAvailableListener() {

        @Override
        public void onImageAvailable(ImageReader reader) {
            mBackgroundHandler.post(new ImageSaver(reader.acquireNextImage(), mFile));

            startActivity(new Intent(getActivity(), DisplayImage.class));
        }

    };

This is the function which saves the image and crops it. I'm not sure if the cropping is right. I just want to be able to display the image in the next activity first. The camera must be working fine when I return for capturing more images later.

 private class ImageSaver implements Runnable {

        /**
         * The JPEG image
         */
        private final Image mImage;
        /**
         * The file we save the image into.
         */
        private final File mFile;

        ImageSaver(Image image, File file) {
            mImage = image;
            mFile = file;
        }

        @Override
        public void run() {
            ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            FileOutputStream output = null;
            try {
                output = new FileOutputStream(mFile);
                output.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                mImage.close();
                if (null != output) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            capturedImage = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

            int width = linearLayout.getWidth();
            int height = linearLayout.getHeight();

            int left = width/6;
            int top = height/8;

            croppedImage = Bitmap.createBitmap(capturedImage, left, top, 5*(width/6), 2*(height/3));

        }

    }
Vaishnavi Killekar
  • 457
  • 1
  • 8
  • 22
  • I am having the exact same problem trying to startActivity inside onImageAvailable method. Have you found a solution to it? – Harry Kane Dec 03 '19 at 15:06

0 Answers0