Akash Jain
Akash Jain

Reputation: 730

Convert ImageProxy to Jpeg or Png

I just started with androidX camera, I'm using it's functionality imagecatpure.takePicture() , and I get ImageProxy as an object, so now my question is how can i convert this to jpeg/png/jpg so I can upload the image through an api?

is there another more efficient way to achieve this?

Upvotes: 2

Views: 3751

Answers (2)

go_cubs
go_cubs

Reputation: 13

Use the toBitmap() method in ImageProxy. Save this bitmap to a file using the compress method in Bitmap. Make sure to apply the appropriate rotation as indicated in the Image Proxy documentation. This is easiest to do on the bitmap.

I do not recommend using the accepted answer because you are essentially forced to wait until the image is saved to do the next thing. The original method in question takePicture(Executor,ImageCapture.OnImageCapturedCallback) includes a callback which has much more flexibility. The main difference is that with this callback you can first notify the user that the picture has been taken and then you can do whatever you need to do next while the image is being saved.

Upvotes: 0

Akash Jain
Akash Jain

Reputation: 730

I have solved the issue by using the below code

    private void takePicture() {
        if (imageCapture != null) {
            ByteArrayOutputStream result = new ByteArrayOutputStream();
            getCacheDir();
            imageCapture.takePicture(new ImageCapture.OutputFileOptions.Builder(result).build(),
                    Executors.newSingleThreadExecutor(),
                    new ImageCapture.OnImageSavedCallback() {
                        @Override
                        public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                            File cache = new File(getCacheDir().getAbsolutePath() + "/" + "captured.png");
                            try (FileOutputStream stream = new FileOutputStream(cache)) {
                                stream.write(result.toByteArray());
                                upload(cache); // your upload function
                            } catch (Exception e) {
                                Log.e(TAG, "onImageSaved: Exception occurred", e);
                            }
                        }

                        @Override
                        public void onError(@NonNull ImageCaptureException exception) {
                            Log.i(TAG, "onError: ", exception);
                        }
                    });
        }
    }

thanks to @Commonsware

Upvotes: 0

Related Questions