Christoph W.
Christoph W.

Reputation: 1024

Java display base 64 byte array in jsp

I have a class called Graphic that creates a new BufferedImage, draws a new Graphics2D and returns this image as base64 encoded String:

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

// Draw background
g2.setColor(Color.decode("#FFFFFF"));
g2.fillRect(0, 0, grafikBreite, grafikHoehe);
g2.setColor(Color.decode("#000000"));

// Draw some rectangles and other stuff...
drawStuff(g2);

ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] imageInByte = {};
try {
  JPEGImageEncoder j = new JPEGImageEncoderImpl(baos);
  j.encode(image);
  imageInByte = baos.toByteArray();
  baos.close();
} catch (IOException e) {
  e.printStackTrace();
}

return javax.xml.bind.DatatypeConverter.printBase64Binary(imageInByte);

In my jsp-File I want to display this image using, where graphic is the previously created base64 byte array:

 <img src="data:image/jpg;base64,<c:out value="${graphic}"/>"/>

The image is displayed, but the problem is that the image has red background and the other colors used are also wrong. If I save the created base64 string as jpeg-File on hard disk, all colors are displayed correctly.

Has someone an idea why HTML displays the image with strange colors?

Thanks for help

Upvotes: 0

Views: 983

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109557

First a bit cleaning up:

g2.setColor(Color.WHITE);
g2.fillRect(0, 0, grafikBreite, grafikHoehe);
g2.setColor(Color.BLACK);
drawStuff(g2);
g2.dispose(); // TODO

Dispose after createGraphics.

Then one could try the more generic, portable ImageIO class. The parametrising for antialiasing and such goes a bit different, but then JPEG is a lossy format anyway. Just to try a different angle.

ImageIO.write(image, "jpg", baos);
baos.close();
imageInByte = baos.toByteArray();

And then I did the closing first. (It has no effect by javadoc.)

One could try .png and a another type, ABGR.

I think ImageIO does the trick, or your code with ABGR.

Upvotes: 2

Related Questions