Search code examples
javaimageaemfileinputstream

Convert image data InputStream to string and from this string back to image does not gives the image


Cq5 image component has the binary image data, I require this data to be exposed in an api.

To do this I tried to get the input stream and read it as String.

InputStream is = jcrnode.getProperty(JcrConstants.JCR_DATA).getBinary().getStream();

String imageData = jcrnode.getProperty(JcrConstants.JCR_DATA).getString();

When trying to write the string to FileOutputStream I dont get the image.

While trying to download the jcr:data manually and open the file image viewer gives the image. But when converting this into string and back doesn't work for me. Any suggestions on this.


Solution

  • Thanks @i.net was able to solve as per ur suggestions above.

    StringBuilder dataUri = New StringBuilder(); dataUri.append("data:image/jpeg;base64"); dataUri.append(StringUtils.newString Utf8(Base64.encodeBase64(imageByteArray,false)));

    dataUri.toString() is the string which can be used as embedded images.

    Sample html below to render base64 image

    <div>
      <p>refer wiki</p>
      <img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
        AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
            9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
    </div>