6

Just created a camera preview in Android with CameraX with the following configuration:

    PreviewConfig previewConfig = new PreviewConfig.Builder()
            .setLensFacing(CameraX.LensFacing.FRONT)
            .setTargetResolution(new Size(720, 720))
            .build();
    Preview preview = new Preview(previewConfig);

Now, the problem is that such target resolution may not be available, in which case the preview will choose a resolution closed to the requested one. What I'm asking here is a way to know which resolution has effectively be chosen by the preview.

Thanks in advance!

Fran Marzoa
  • 4,293
  • 1
  • 37
  • 53

2 Answers2

5

Actually it is possible. I've found out after a little bit of source code digging that after calling bindToLifecycle on your cameraProvider:

camera = cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, previewUseCase, imageCaptureUseCase, analyzerUseCase)

You will be able to retrieve resolution selected for each applicable usecase:

val captureSize = imageCaptureUseCase.attachedSurfaceResolution ?: Size(0, 0)
val previewSize = previewUseCase.attachedSurfaceResolution ?: Size(0, 0)

Hope this helps

Marcin Bak
  • 1,410
  • 14
  • 25
  • Thanks Marcin, this will be useful for me when I update my project dependencies. I hope it's useful for @Dmytro Batyuk too. – Fran Marzoa May 18 '20 at 13:45
  • 4
    `attachedSurfaceResolution` is library restricted now, we can use it suppressing the warning but we should ask for a new public API probably – MatPag Mar 18 '21 at 15:37
  • Hey @Marcin Back You can now use the unrestricted methods imageCaptureUseCase.getResolutionInfo().getResolution() (Java code). Would you like to update your answer? – Fran Marzoa May 15 '23 at 09:25
1

Ok, I found myself a solution.

    preview.setOnPreviewOutputUpdateListener(new Preview.OnPreviewOutputUpdateListener() {
        @Override
        public void onUpdated(Preview.PreviewOutput output) {
             ...
             Size resolution = output.getTextureSize();
             ...
        }
    });
Fran Marzoa
  • 4,293
  • 1
  • 37
  • 53
  • 2
    Unfortunately CameraX doesn't provide such API any more. I haven't found alternative yet – Dmytro Batyuk May 14 '20 at 04:43
  • @DmytroBatyuk I'm sorry to hear that. I hope they add something in a further version, or improve the docs explaining how things like this that should be pretty common can be done. – Fran Marzoa May 15 '20 at 07:08
  • 1
    NP, just mentioned this for other people who are also looking for something similar to save their time – Dmytro Batyuk May 15 '20 at 08:49
  • 2
    @DmytroBatyuk please check my answer. I've found a way to retrieve the final resolution. – Marcin Bak May 18 '20 at 16:13