androidandroid-cameraandroidx

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?


Solution

  • 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