mad
mad

Reputation: 1047

JasperReports with Java Bean: Failed to render image (the field of InputStream type)

Input: 1. class with member InputStream

public class Dateien {
...
   private InputStream payload = null;
...
   public InputStream getPayload() {
       return payload;
   }
   public void setPayload(InputStream payload) {
     this.payload = payload;
   }
}
  1. payload contains Stream with image (jpg or other formats)
  2. Jasper report with text field (class=java.lang.String, expression=$F{file.payload}) shows me right string in report

    java.io.ByteArrayInputStream@6aa27760
    
  3. but when I create Image field in report (class=java.io.InputStream, expression=$F{file.payload})

  4. I get exception

     SEVERE: Servlet.service() for servlet [appServlet] in context with path [/abc] threw exception [Request processing failed; nested exception is
     net.sf.jasperreports.engine.JRException: Image read failed.] with root cause
     net.sf.jasperreports.engine.JRException: Image read failed.
     at net.sf.jasperreports.engine.util.JRJdk14ImageReader.readImage(JRJdk14ImageReader.java:73)
    

What should I do to fix the problem?

By the way: I tried to get the image stream via HTTP in browser and I see good rendered image. So I see the stream is OK and not corrupted.

Upvotes: 1

Views: 7129

Answers (1)

Alex K
Alex K

Reputation: 22857

The exception raised in the net.sf.jasperreports.engine.util.JRJdk14ImageReader class, in line number 73.

The source code of JRJdk14ImageReader.readImage(byte[]) method:

public Image readImage(byte[] bytes) throws JRException
{
    InputStream bais = new ByteArrayInputStream(bytes);

    Image image = null;
    try
    {
        image = ImageIO.read(bais);
    }
    catch (Exception e)
    {
        throw new JRException(e);
    }
    finally
    {
        try
        {
            bais.close();
        }
        catch (IOException e)
        {
        }
    }

    if (image == null)
    {
        throw new JRException("Image read failed."); // the line #73
    }

    return image;
}

As we can see, the Exception is thrown in case the image is still null.

You should check that you are really passing the array of bytes (byte[]) to the report as payload field.

Upvotes: 1

Related Questions