0

I am getting my image as base 64 decoded string in my spring mvc application. e.g.

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABUUAAAkFCAYAAAD3GsjUAAAgAElEQVR4nOy9eXSb932vqc50fJs2Z+6ZOefeO2dmbm/aSW9ve+MmrZv2Nmmm7TROs7q2Yzl2HNWxtmihZNmSLMd24t=

I am trying save it as a png image:

byte[] imageByte = Base64.decodeBase64(base64encodedImage);    
String directory = "D:\\Image Capture\\sample.png";
FileOutputStream outputStream = new FileOutputStream(directory);            
outputStream.write(imageByte);
outputStream.flush();
outputStream.close();

but it is saving my image as

Imaged saved on file system

I am not able to figure out the reason. This encoded image is obtained using canvas.toDataUrl in javascript. It opens in browser tab perfectly.

Priyank Thakkar
  • 4,752
  • 19
  • 57
  • 93
  • Every image has a format. Which one does yours have? You say you want to save it as PNG, but which format is it in currently? If you have it for instance in JPG, then you first have to convert it to PNG. Therefore, your steps are: 1. Decode Base64, 2. Convert X-format to PNG, 3. Save your file. – Socrates Dec 16 '14 at 17:08
  • @Socrates : from encoded image data I can see it's png because it starts with data:image/png – Priyank Thakkar Dec 16 '14 at 18:16
  • Try out one thing! Take an existing working PNG and code it to Base64. Then use your Java code from above and decode it again. This way you'll see the functionality! – Socrates Dec 18 '14 at 11:07

1 Answers1

3

Finally I have figured out.

Answer on this link helped.

The encoded Image I received:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABUUAAAkFCAYAAAD3GsjUAAAgAElEQVR4nOy9eXSb932vqc50fJs2Z+6ZOefeO2dmbm/aSW9ve+MmrZv2Nmmm7TROs7q2Yzl2HNWxtmihZNmSLMd24t=

The encoded image part starts after the phrase below:

data:image/png;base64,

I had to skip that string and then decoded image.

Also I have figured out from the same thread that the extra String shouldn't stop us from decoding.

In the same forum an approach is suggested that while converting encoded image user:

InputStream stream = new ByteArrayInputStream(Base64.decode(image.getBytes(), Base64.DEFAULT));

Refer to @Wand Maker's answer in the same thread.

Community
  • 1
  • 1
Priyank Thakkar
  • 4,752
  • 19
  • 57
  • 93