3

I am using Apache httpclient to call a REST web service. This service returns image in base64 format. I want to convert this to image in png format but I don't want to save this image file. Reason being there are more than 10000 users and if I keep saving all the images, it would consume a lot of memory.

I am using JDK 1.7

Is it possible to achieve this ?

user972418
  • 817
  • 3
  • 25
  • 58
  • This might be relevant: http://stackoverflow.com/questions/7178937/java-bufferedimage-to-png-format-base64-string – Marc Baumbach Feb 01 '15 at 06:38
  • What format is the image in to start off with, in the base64 string from the client?? – Adam Feb 01 '15 at 06:51
  • You can put everything together in memory (without ever writing to disk) using streams but it will use memory of a constant factor greater than one times the space needed for the image itself. – 5gon12eder Feb 01 '15 at 06:53

2 Answers2

0

Create a BufferedImage instance from whatever format, assuming that is supported by ImageIO... I'm guessing this is from disk - you've not said in your question

    BufferedImage original = ImageIO.read(new FileInputStream("test.png"));

Write as PNG into a ByteArrayOutputStream

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(original, "png", outputStream);

Convert resultant byte array back to base64.

String output = DatatypeConverter.printBase64Binary(outputStream.toByteArray());
System.out.println(output);
Adam
  • 35,919
  • 9
  • 100
  • 137
0

Shouldn't be hard - you can use memory-based streams instead of file-based ones:

  1. Decode the base64 image using, e.g. Apache Common's codec, into a byte array.
  2. Create an input stream from the byte array, using ByteArrayInputStream.
  3. Read the image from the stream via ImageIO.read
  4. Save to to PNG and output as a stream to the client.
Michael Bar-Sinai
  • 2,729
  • 20
  • 27
  • Thanks for your response. Could you please provide a code snippet for this. I am fairly new to this and don't really have any idea. Let me know if you need any further information. – user972418 Feb 01 '15 at 14:32