Create a JPEG dynamically in JAVA with Spring

The problem:

I have a JAVA Spring web application running in a Tomcat and I want to display in a web page a jpeg created dynamically from the content of a double[][] java array.

The solution:

First we create a method which creates a BufferedImage object from a double[][] array where our data will be stored. We pass as arguments the width and height in pixels.

public static BufferedImage generate(double[][] data, int pixelsWidth, int pixelsHeight ) throws Exception{

        double x =0,y = 0;
        BufferedImage bi = new BufferedImage( pixelsWidth, pixelsHeight,  BufferedImage.TYPE_3BYTE_BGR );
        Graphics2D g=(Graphics2D)bi.getGraphics();

        int w=data[0].length;
        int l=data.length;
        double Dy=(double)pixelsHeight/(double)l;
        double Dx=(double)pixelsWidth/(double)w;
        int height = (int)Math.ceil(Dy);
        int width = (int)Math.ceil(Dx);	
        int gap=(int)Math.ceil(width/4);

    	double max=-Double.MAX_VALUE;
    	for (int i=0;i<l;i++){
    		for (int j=0;jmax) max=data[i][j];    	
        int norm=(int)(Integer.MAX_VALUE/max);

        g.setColor( Color.WHITE);
        g.fillRect( 0, 0 , pixelsWidth,pixelsHeight); 
        for( int i =0; i < l; i++ ){        	
            for( int j =0; j < w; j++ ){            	
               g.setColor( new Color((int)data[i][j]*norm));                
               g.fillRect( (int)x, (int)y , width-gap,height);        

        return bi;

Now we need to create a method inside a Spring controller which will listen for the HTTP petitions for the JPEG image. This method will call the previous generate method for converting the double[][] array into a BufferedImage object and will redirect to the HTTP output stream.

@RequestMapping(value = "/image/{id}", method=RequestMethod.GET)
public ResponseEntity matrixMinPlus(@PathVariable("id") Long id,@RequestParam(value="width", required = false) Integer width, @RequestParam(value="height", required = false) Integer height){
    	DataMatrix dataMatrix = DataMatrix.findDataMatrix(id);		
	try {
		if (width==null) width=100;
		if (height==null) height=100;

		BufferedImage img=ArrayUtils.generate(dataMatrix.getRawData(),width,height);
		ByteArrayOutputStream baos=new ByteArrayOutputStream();
		ImageIO.write(img, "jpg", baos );
		byte[] imageInByte=baos.toByteArray();

		final HttpHeaders headers = new HttpHeaders();
		headers.setContentType(new MediaType("image","jpeg"));			
		return new ResponseEntity(imageInByte, headers, HttpStatus.CREATED);
	} catch (Exception e) {
	return null;

Now all the HTTP request that will go to the relative URL defined by /image/{id} where {id} is an identifier of our desired DataMatrix object will receive as response a JPEG.

The final jpeg image can be something like this:

Matrix without predefined colormap


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s