Harsh Sharma
Harsh Sharma

Reputation: 11242

Show Image stored in byte array form in java servlet

I have image stored as a byte[]. Now I want to display it from a Java servlet. I am using this code:

response.setContentType("image/gif");
OutputStream out = response.getOutputStream();
out.write(img); // image is of byte[] type.
out.flush();
out.close();

But I am getting the error "The image cannot be displayed because it contains an error."

Upvotes: 2

Views: 1872

Answers (1)

Harsh Sharma
Harsh Sharma

Reputation: 11242

Actually the reason was totally different for this error.I am performing my task in two steps =>

First to convert image into byte[] and storing into hbase. And then getting the byte[] from hbase and showing it through browser.

In the question I mentioned the code of 2nd part, but the actual problem that was causing the error was in 1st part. The reason of the error was:

Initially I was converting the image into byte[] using the code

    File imgPath = new File(ImageName);
    BufferedImage bufferedImage = ImageIO.read(imgPath);

    // get DataBufferBytes from Raster
    WritableRaster raster = bufferedImage.getRaster();
    DataBufferByte data = (DataBufferByte) raster.getDataBuffer();

    return (data.getData());

Which was causing the error

"Exception in thread "main" java.lang.IllegalArgumentException: image == null!
    at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925)
    at javax.imageio.ImageIO.getWriter(ImageIO.java:1591)
    at javax.imageio.ImageIO.write(ImageIO.java:1520)
    at com.medianet.hello.HbaseUtil.main(HbaseUtil.java:138)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
"

When I changed the code to

    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    BufferedImage img=ImageIO.read(new File(ImageName));
    ImageIO.write(img, "jpg", baos);
    baos.flush();

    return baos.toByteArray();

It worked.

Upvotes: 1

Related Questions