Convert base64 string to image from ESP32-cam

66 Views Asked by At

I'm trying to convert a base64 string to an image but nothing works, I am receiving this base64 String in a firebase from ESP32-CAM: this is the image string here

this is the code:

databaseReference.child("esp32-cam-data").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (snapshot.exists()){
                    try {
                        String data = snapshot.getValue().toString();
                        String img = data.split(",")[1];
                        Log.i("Image data", img);
                        Bitmap bm = stringToBitMap(img);
                        cameraPreview.setImageBitmap(bm);

                        
                    }catch(Exception e){
                        Log.e("Image Exeption", e.toString());
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
  • from string to image function:
public Bitmap stringToBitMap(String encodedString) {
        try {
            byte[] encodeByte = Base64.decode(encodedString, Base64.DEFAULT);
            return BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
        } catch (Exception e) {
            e.getMessage();
            return null;
        }
    }
  • log error:
2024-03-15 04:24:31.356 29923-29923 skia                    com.nidcam.nidcam                    D  --- Failed to create image decoder with message 'unimplemented'

I tried changing and using Picasso and Glide -with picasso:

try {
       String data = snapshot.getValue().toString();
       Picasso.get()
           .load(data)
           .into(cameraPreview);
}catch(Exception e){
       Log.e("Image Exeption", e.toString());
}

-with glide:

try {
       String data = snapshot.getValue().toString();
       Glide.with(getApplicationContext())
           .load(data)
           .into(cameraPreview);
}catch(Exception e){
       Log.e("Image Exeption", e.toString());
}

and nothing work, i with u help me please.

3

There are 3 best solutions below

1
Aimar On

As i can see your code, i think your code is ok but your base64 encoding is wrong i have never seen a base64 that contains

% symbol

base64 contains only

(A-Z, a-z, 0-9, +, /)

reencode your base64 data with proper base64 encoding

Hope it Helps!

0
Fuzz of the Interwebs On

The problem that stands out is you are using Bitmap to compute a JPEG. The image formats are totally different.

Thanks Aimar, you gave me a clue: the Base64 string needed to be URL decoded first

Decode the string from URL to text, it'll be in Base64 format. Decode the Base64 string to image using JPEG format.

This is some Java code that could do the exact process

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Base64;
import java.net.URLDecoder;

public class DataURIImageDecoder {
    public static void main(String[] args) {
        String dataURI = args[0];
        
        BufferedImage image = decodeDataURIImage(dataURI);
        if (image != null) {
            System.out.println("Image successfully decoded.");
        } else {
            System.out.println("Failed to decode the image.");
        }
    }

    public static BufferedImage decodeDataURIImage(String dataURI) {
        try {
            String decodedURI = URLDecoder.decode(dataURI, "UTF-8");
            String[] parts = decodedURI.split(",");
            if (parts.length != 2 || !parts[0].startsWith("data:")) {
                throw new IllegalArgumentException("Invalid Data URI format");
            }
            String base64String = parts[1];
            byte[] decodedBytes = Base64.getDecoder().decode(base64String);
            ByteArrayInputStream bis = new ByteArrayInputStream(decodedBytes);
            BufferedImage image = ImageIO.read(bis);
            bis.close();

            return image;
        } catch (IOException e) {
            System.out.println("Error decoding image: " + e.getMessage());
            return null;
        }
    }
}
2
blackapps On

That file is no base64 encoded string.

It starts with data:image/jpeg;base64,

Remove that to obtain the base64 encoded string.