Search code examples
androidandroid-cameraandroid-imageandroid-camera2image-reader

How to convert .png/.jpg format file to android.media.Image object?


I have an android app and noticed that it is onImageAvailable(ImageReader imagereader) function that takes images from the ImageReader when available and processes them. My aim is to manipulate that Image object so that it would process a png file instead of taking that image from the camera. So, I want to change

    this.imagereader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
                    public final void onImageAvailable(ImageReader imageReader) {
                        Image image = imageReader.acquireLatestImage();
                    }
                }, this.thread1);

to something like


    this.imagereader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
                    public final void onImageAvailable(ImageReader imageReader) {
                        Image image = //png path;
                    }
                }, this.thread1);

Is it possible?


Solution

  • Image is a system resource backed by hardware buffers and you can't just implement your own variant of it. What you can do however is to create an ImageReader with the desired parameters (you likely want to use the same size and format as the original app expect), take a surface from it and draw your png to that surface. You can use a drawing method that suites best your needs - either call lockCanvas and draw on CPU or use Vulkan / OpenGL / Renderscript (depending on the image format an usage flags some of these methods might not be possible).

    Also instead of creating an Image using another ImageReader and injecting it into onImageAvailable, I would consider using the existing ImageReader, but replace the producer of the images - camera in your case - with your own one. So basically you can take surface from the existing ImageReader and instead of passing it into camera session, just draw into it yourself.