The image can not be displayed because it contains errors in jsp

advertisements

I'm trying to save and show image from mongodb database. I save it in database formatted in base-64 String. for example this is one of those images:

"data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEAYABgAAD/7gAOQWRvYmUAZAAAAAAB/+EN/kV4aWYAAE1NACoAAAAIAAgBMgACAAAAFAAAAG4BOwACAAAACwAAAIJHRgADAAAAAQAFAABHSQADA......

This is findImage service which changes string format of image to an array of bytes:

 public byte[] findImage(String id)
    {
        String str = chRepository.findImage(id);
        byte[] b = str.getBytes();
        return b;
    }

and this is findImage in controller class:

   @GetMapping("/findImage/{id}")
    public byte[] findImage(@PathVariable String id) throws IOException
    {
        byte[] bb = IOUtils.toByteArray(new ByteArrayInputStream(chService.findImage(id)));
        return bb;
    }

I make a url to show images in my script file:

<script>
        function makeURL(val, row) {

            if (val){
                return '<a target="_blank" href=  "'  +window.location.href+  'ch/findImage/' + val + '">image</a>';
            }
        }
    </script>

but when calling a url like this one:

http://localhost:8080/ch/findImage/5

it gives the error: the image cannot be displayed because it contains errors.

Note: I guess there is a problem with service findImage function where it changes base-64 String to an array of byte[], but I don't know how to change it to a correct format.


You're calling only getBytes() on the string but there are two points you have to regard.

  1. The string has a special syntax for inlineing image data inside a HTML page. The first part contains the MIME type and ;base64 indicating that the following part after the comma is Base64 encoded.

  2. getBytes() gives you the byte representation of the string as is. This is not what you want. Because Base64 is a special encoding, you have to treat it specially. You can use the standard class java.util.Base64 for this.

Example:

/**
 * Decodes the Base64 part to bytes.
 *
 * @param img An inline data encoded in Base64 like <code>"data:image/jpeg;base64,/9j/4AAQSkZJRg..."</code>.
 *
 * @return Decoded data part
 */
public static byte[] parseImageString(String img) {
  // Avoid a NPE
  if(img == null) {
    return null;
  }

  // Use only the part after the comma
  final int pos = img.indexOf(',');
  if(pos >= 0) {
    final String base64Part = img.substring(pos + 1);
    final Base64.Decoder base64Decoder = Base64.getDecoder();
    return base64Decoder.decode(base64Part);
  } else {
    return null;
  }
}