How can i convert String to Bitmap image on Java

70 Views Asked by At

There is a bitmap codes in the text file. I need to convert these codes as String to Bitmap and display them to the user on the screen. I wrote a code like below, but decodedByte is null. Where am I making a mistake?

try {
   BufferedReader reader = Files.newBufferedReader(Paths.get("/data/user/0/com.example.lockertestapplication/files/text.txt"), StandardCharsets.UTF_8);
   StringBuilder data = new StringBuilder();
   String line;
   while ((line = reader.readLine()) != null) {
      data.append(line);
   }
   reader.close();
   String text = data.toString();
   byte[] decodedString = Base64.decode(text, Base64.DEFAULT);
   Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
   img.setImageBitmap(decodedByte);
                
} catch (IOException e) {
   e.printStackTrace();
}
2

There are 2 best solutions below

0
jatan sanghvi On

Issue might be related to the following:

  1. String in your text file might not be correctly base64-encoded or corrupted.

2.In your code you are using Base64 Default for decoding instead of that try Base64.NO Wrap or other flags

3.It is also possible that the bitmap is too large for the memory, this is a possibility if you are uncourting OutOfMemoryError along with this error

0
Sohail Anwar On

Issue might be in removing Base64 identifier from Base64 encoded text. First, we need to split our Base64 string to get rid of the first part before “,”(comma)

String text = base64String.split(",")[1];

And then you are good to with your implemented method

byte[] decodedString = Base64.decode(base64Image, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageView.setImageBitmap(decodedByte);