How/Can I use base64 as image source in a Jasper Report template?
Passing parameter as String
makes jasper report believe its a absolute file path, so you need another class. The most obvious would be java.awt.Image
or java.io.InputStream
.
I choose java.io.InputStream
since this will require less code, so the first thing we need to do now is to decode
the base64
image String
.
There are several Base64 class that will do the job, I choose the org.apache.commons.codec.binary.Base64
since apache commons-codec.jar
is already distributed with jasper report (dependencies). The decode will give us a byte array byte[]
, so now we need only to add a ByteArrayInputStream
The java code would be:
InputStream stream = new ByteArrayInputStream(Base64.decodeBase64(smileyfaceimage.getBytes()));
Time to pass it into the jasper report imageExpression
<image scaleImage="FillFrame" onErrorType="Blank">
<reportElement x="167" y="62" width="363" height="171" backcolor="#333333"/>
<imageExpression class="java.io.InputStream"><![CDATA[new java.io.ByteArrayInputStream(org.apache.commons.codec.binary.Base64.decodeBase64($P{smileyfaceimage}.getBytes()))]]></imageExpression>
</image>
Hope for the best and press the preview:
Important notice: The smileyfaceimage
needs to be without:data:image/png;base64,
EDIT: The problem of the OP (comments) was that with old jasper report lib (3.0) you need to specify the class in the imageExpression
@see class="java.io.InputStream"
the post has been update consequently since this works also in 6.0.
Java 8+ without external libraries:
<imageExpression><![CDATA[javax.imageio.ImageIO.read(new java.io.ByteArrayInputStream(Base64.getDecoder().decode($P{barcodeHeader})))]]></imageExpression>
If that doesn't work, this should definitely:
<imageExpression><![CDATA[javax.imageio.ImageIO.read(new java.io.ByteArrayInputStream(java.util.Base64.getDecoder().decode($P{barcodeHeader})))]]></imageExpression>
You need to decode the image somehow, e.g. use an imageExpression:
<image scaleImage="RetainShape" hAlign="Center" vAlign="Bottom" isUsingCache="false">
<reportElement uuid="53a340b3-7d64-4104-9e9f-0f603059579a" key="Logo_Footer" x="55" y="760" width="370" height="42"/>
<imageExpression><![CDATA[new java.io.StringBufferInputStream(new org.w3c.tools.codec.Base64Decoder(" Base 64 String Data ").processString())]]>
</imageExpression>
</image>
I'm using this to embed images, but it should work with a variable, field or parameter too.