How to add image as parameter from projects classpath in jasper reports

We always pass in the image instead of the InputStream. First load up the image and set it in the parameter map:

BufferedImage image = ImageIO.read(getClass().getResource("/images/IMAGE.png"));
parameters.put("logo", image );

Then the parameter is just defined like:

<parameter name="logo" class="Object" isForPrompting="false">
  <parameterDescription><![CDATA[The letterhead image]]></parameterDescription>
  <defaultValueExpression><![CDATA[]]></defaultValueExpression>
</parameter>

And when placed in the report it looks like:

<image>
  <reportElement x="324" y="16" width="154" height="38"/>
  <imageExpression><![CDATA[$P{logo}]]></imageExpression>
</image>

You can easily get the URL form the classpath/classloader. This is a valid input for <imageExpression> and therefore you can use it to embed an image in your pdf. The following worked for me:

Setting the parameter:

URL url = this.getClass().getClassLoader().getResource("pdf/my_image.tif");
parameters.put("logo", url);

Declaration in the report:

<parameter name="logo" class="java.net.URL">
    <defaultValueExpression><![CDATA[]]></defaultValueExpression>
</parameter>

Usage in the report.

<image>
   <reportElement x="100" y="30" width="135" height="30"/>
   <imageExpression><![CDATA[$P{logo}]]></imageExpression>
</image>

Some additional observations

  • Before I was using InputStream and it worked fine when displaying the image only once. When I needed to repeat the image, InputStream did not work because the stream is consumed on the first display so it can not be used after that. I did not find an easy way to reset it.
  • I found out that URLs could be used from here: http://jasperreports.sourceforge.net/sample.reference/images/index.html

I did not manage to get it working with any of those methods, I was having the error :

 Error evaluating expression for source text

at compiling the report in java.

In java you have to get your image to an inputstream so either

byte[] image = imageRepository.getLogo();
InputStream logo= new ByteArrayInputStream(image);
parameters.put("logo",logo);

because I am getting the image as a byteArray from a database, but if you have it somewhere in your JAR:

ResourceLoader resourceLoader;
InputStream logo= resourceLoader.getResource("classpath:/image/logo.jpg").getInputStream();
parameters.put("logo",logo);

Then in the in jrxml it simply gives :

    <parameter name="logo" class="java.io.InputStream"/>

    <image scaleImage="RealSize">
        <imageExpression><![CDATA[$P{logo}]]></imageExpression>
    </image>