Jump to content
Changes to the Jaspersoft community edition download ×

Tip: embedding images in reports


joshhighley

Recommended Posts

I've saw several posts lately about problems linking to images from reports.  I thought I'd share this tip:

I created a report that uses a couple of images to indicate the status of some automated services (running or not running) for a dashboard.  I didn't want to mess with handling the images separate from the report, so I used this method to embed the images in the jrxml itself:

1) Base64 encode the image.  I used the online utility at http://www.motobit.com/util/base64-decoder-encoder.asp    Note that I have no ties to this site whatsoever, it's just something I found to be useful and it works.

2) In your report, create a variable of type String and set the variable expression to the Base64 encoded string from step 1

3) Put the image element in your report with class java.io.InputStream  I also set scaling to retain shape.

4) For the image expression use:

new java.io.StringBufferInputStream( new org.w3c.tools.codec.Base64Decoder($V{MY_IMAGE}).processString() )

The Base64 decoder class is included with JasperServer and is already on the classpath.  I tested this successfully with image formats GIF, JPEG, PNG, and BMP.  (I ended up using PNG by the way)

I think it should also be possible to use class java.awt.Image (BufferedImage) created by ImageIO.load() from a byte array input stream, but this didn't work for me, even though using InputStream directly does.

Thanks,

Josh

Link to comment
Share on other sites

  • 2 years later...
  • Replies 6
  • Created
  • Last Reply

Top Posters In This Topic

Hello.

          I have to display  object as image  inside a list component in iReport based on a particular count(here using intNote  ). I have tried this way...But no image is dispalyed...while using image path from specific location images are displayed...how can i dispaly object as  images inside a list component ..please any one help me as soon as possible.......Thanks.........

 

<componentElement>
                <reportElement x="130" y="72" width="25" height="35"/>
                <jr:list xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd" printOrder="Horizontal" ignoreWidth="true">
                    <datasetRun subDataset="Q2">
                        <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.JREmptyDataSource($F{intNote})]]></dataSourceExpression>
                    </datasetRun>
                    <jr:listContents height="35" width="25">
                        <image isUsingCache="false">
                            <reportElement x="3" y="10" width="16" height="17" forecolor="#FFFFFF"/>
                            <graphicElement>
                                <pen lineWidth="1.25"/>
                            </graphicElement>
                            <imageExpression class="java.awt.Image"><![CDATA[$F{strVert}]]></imageExpression>
                        </image>
                    </jr:listContents>
                </jr:list>
            </componentElement>

 

 

Link to comment
Share on other sites

  • 3 months later...

Thanks for the info, I was looking for a way to embed images in ireport & came across your post..

I just faced an issue & wanted to share the solution with everyone else..

I guess for your service status, you have used small size images, in my case I was trying to embed a high quality banner so the resulted Base64 was big & upon compilation ireport throw the error "the java string is too long..."

so to fix it, I have set the variable class to java.lang.StringBuffer & the initial variable expression to :

new java.lang.StringBuffer().append("subset of the base64 data").append("subset2").append("subset3").........

& in the image expression add .toString() to your variable...

 

If you have Python installed you can use the below function to automatically create the initial variable expression for large images.

 

 

 

Code:
def test():	import random, os, time, base64	img = r'C:\Documents and Settings\Owner\Desktop\iReport\images\Banner.jpg'	open_img = open(img, 'rb')	imgData = base64.b64encode(open_img.read())	open_img.close()	imgLen = len(imgData)	forJava = 'new java.lang.StringBuffer()'	whole = ''	for i in xrange(0, imgLen, 1000):		forJava += '.append("%s")'%imgData[i: i + 1000]		whole += imgData[i: i + 1000]        #write it to text file	open_file = open(r'C:\Documents and Settings\Owner\Desktop\iReport\images\data.txt', 'w')	open_file.write(forJava )	open_file.close()	#verify that image is reconstructed properly	rpath = r'C:\Documents and Settings\Owner\Desktop\iReport\images\_\%s'%random.random() + '.' + img.split('.')[1]	open_img = open(rpath, 'wb')	open_img.write(base64.b64decode(whole))	open_img.close()	os.startfile(rpath)	time.sleep(2)	os.remove(rpath)
Link to comment
Share on other sites

  • 2 years later...
  • 1 year later...

This doesn't work in JR 6.0.3, even though it did in 5.6.1.

I tested additionally with this code:

**************************************************

    public static void main(String[] args) {
        System.out.println("Starting img test");
        String b64img = "her goes image encoded in base64";
        try (
                java.io.InputStream is = new java.io.ByteArrayInputStream(new sun.misc.BASE64Decoder().decodeBuffer(b64img));
            ) {
            
            java.awt.image.BufferedImage bi = javax.imageio.ImageIO.read(is);
            System.out.println("Read image: "+bi);
        } catch (Throwable t) {
            System.err.println("Error: "+t);
        }
    }
**************************************************

And it works fine.

I have Java 8 x86_64 running on Windows 7 x86_64.

Link to comment
Share on other sites

  • 1 year later...
  • 10 months later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...