JasperReports

now browsing by category

 

Displaying DB backed image in a JasperReport

JasperReports

The JasperReports Library is a Java based open source reporting engine. We have been using it for a while now to create reports. Most of the images included inside the reports were available directly in our web app, so they were included using an URL.

Recently we had a special case, when we wanted to use some logo images that we already had stored in a MySQL database (same format and same sizes). With JasperReports you can get data to be displayed directly from the database (Multiple other datasources are also available, see link). So why not being able to also get the images directly from the database.

Here is the table we are dealing with:

CREATE TABLE `brand` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `code` varchar(10) DEFAULT NULL,
  `description` text,
  `logo` blob,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_orgBrand_code` (`brand_code`),
) ENGINE=InnoDBDEFAULT CHARSET=utf8

The images were previously loaded in the databases using a command such as:

UPDATE `brand`
SET logo = LOAD_FILE('/path/to/someLogo.gif')
WHERE brand_id = 1;

!!! In our case the image was on the server machine in a place where the MySQL server has access; We also set the permission 777, just in case.

Here is the jrxml

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="ImageFromBlob" language="groovy" pageWidth="400" pageHeight="200" columnWidth="360" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="4901763a-a0b1-4631-a52f-7488b37c29aa">
	<property name="ireport.zoom" value="1.0"/>
	<property name="ireport.x" value="0"/>
	<property name="ireport.y" value="0"/>
	<queryString>
		<![CDATA[ SELECT `name`, `logo` FROM `brand WHERE id = 1 ]]>
	</queryString>
	<field name="name" class="java.lang.String"/>
	<field name="logo" class="java.io.InputStream"/>
	<background>
		<band splitType="Stretch"/>
	</background>
	<title>
		<band height="160" splitType="Stretch">
			<image onErrorType="Icon">
				<reportElement uuid="9cb179cc-9434-42a0-817e-66963aed90e0" x="18" y="33" width="317" height="114"/>
				<imageExpression><![CDATA[$F{logo}]]></imageExpression>
			</image>
			<staticText>
				<reportElement uuid="74dad9ea-7c7e-4f7d-b184-3cf04f1194db" x="0" y="0" width="208" height="20"/>
				<textElement/>
				<text><![CDATA[Image loaded from BLOB]]></text>
			</staticText>
		</band>
	</title>
</jasperReport>

There you go. The one and only trick is to set the JR fieldType to be java.io.InputStream.