Tushar Deshpande
Tushar Deshpande

Reputation: 448

Convert base64 string to image at server side in java

I have base64 String which I want to convert back to image irrespective of image format at server side. I tried it by using following code, image is getting created but when I am trying to preview it, showing error could not load image.

public void convertStringToImage(String base64) {
        try {
            byte[] imageByteArray = decodeImage(base64);

            FileOutputStream imageOutFile = new FileOutputStream("./src/main/resources/demo.jpg");
            imageOutFile.write(imageByteArray);
            imageOutFile.close();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "ImageStoreManager::convertStringToImage()" + e);
        }
    }


    public static byte[] decodeImage(String imageDataString) {
        return Base64.decodeBase64(imageDataString);
    }

what should I do so that my image will look properly?

Upvotes: 0

Views: 8404

Answers (2)

Grzegorz Gajos
Grzegorz Gajos

Reputation: 2363

Your code looks fine. I can suggest however some more debugging steps for you.

  1. Encode your file manually using, for example, this webpage
  2. Compare if String base64 contains exact same content like you've got seen on the page. // if something wrong here, your request is corrupted, maybe some encoding issues on the frontend side?
  3. See file content created under ./src/main/resources/demo.jpg and compare content (size, binary comparison) // if something wrong here you will know that actually save operation is broken

Remarks:

  • Did you try to do .flush() before close?
  • Your code in current form might cause resource leakage, have a look at try-with-resources

Upvotes: 1

SujitKumar
SujitKumar

Reputation: 132

Try this:

public static byte[] decodeImage(String imageDataString) {
    return org.apache.commons.codec.binary.Base64.decodeBase64(imageDataString.getBytes());
}

Upvotes: 0

Related Questions