Struts 2 dynamic image example

In this tutorial, we show you how to generate a dynamic image in Struts 2, via custom result type. For example,


<img src="<s:url action='ImageAction?imageId=darksouls.jpg' />" />

The value of imageId is the image name in your server path. In above case, the ImageAction class will output the image file based on the imageId paramater.

Tools and Struts used in this tutorial :

  1. Struts 2.3.1.2
  2. Eclipse 3.7
  3. Maven 3

1. Directory Structure

Directory structure of this tutorial. Review the image file path.

struts2 dynamic image directory structure

2. Action class

File : DisplayAction.java – A normal action, do nothing.


package com.mkyong.image.action;

import com.opensymphony.xwork2.ActionSupport;

public class DisplayAction extends ActionSupport  {

}

File : ImageAction.java – core action class, to get the image based on the provided imageId parameter and convert it into bytes array.


package com.mkyong.image.action;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;

public class ImageAction extends ActionSupport implements ServletRequestAware {

	byte[] imageInByte = null;
	String imageId;

	private HttpServletRequest servletRequest;

	public String getImageId() {
		return imageId;
	}

	public void setImageId(String imageId) {
		this.imageId = imageId;
	}

	public ImageAction() {
		System.out.println("ImageAction");
	}

	public String execute() {
		return SUCCESS;
	}

	public byte[] getCustomImageInBytes() {

		System.out.println("imageId" + imageId);

		BufferedImage originalImage;
		try {
			originalImage = ImageIO.read(getImageFile(this.imageId));
			// convert BufferedImage to byte array
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ImageIO.write(originalImage, "jpg", baos);
			baos.flush();
			imageInByte = baos.toByteArray();
			baos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return imageInByte;
	}

	private File getImageFile(String imageId) {
		String filePath = servletRequest.getSession().getServletContext().getRealPath("/");
		File file = new File(filePath + "/Image/", imageId);
		System.out.println(file.toString());
		return file;
	}

	public String getCustomContentType() {
		return "image/jpeg";
	}

	public String getCustomContentDisposition() {
		return "anyname.jpg";
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.servletRequest = request;

	}

}

3. Custom Result Type

A custom result type, and output the image to browser.

File : CustomImageBytesResult.java


package com.mkyong.image.result;

import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
import com.mkyong.image.action.ImageAction;

public class CustomImageBytesResult implements Result {

	public void execute(ActionInvocation invocation) throws Exception {
 
		ImageAction action = (ImageAction) invocation.getAction();
		HttpServletResponse response = ServletActionContext.getResponse();

		response.setContentType(action.getCustomContentType());
		response.getOutputStream().write(action.getCustomImageInBytes());
		response.getOutputStream().flush();
		
	}

}

4. Struts.xml

See how everything is linked together.

File : struts.xml


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

	<package name="image" namespace="/Image" extends="struts-default">

		<result-types>
			<result-type name="imageResult"
				class="com.mkyong.image.result.CustomImageBytesResult" />
		</result-types>

		<action name="Display" class="com.mkyong.image.action.DisplayAction">
			<result>pages/display.jsp</result>
		</action>

		<action name="ImageAction" class="com.mkyong.image.action.ImageAction">
			<result name="success" type="imageResult">
			</result>
		</action>

	</package>

</struts>

5. JSP Page

A JSP page to display the dynamic image via ImageAction.

File : display.jsp


<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head></head>
<body>
	<h1>Struts 2 Dynamic Image Example</h1>

	<img src=" <s:url action='ImageAction?imageId=darksouls.jpg' />" />

</body>
</html>

6. Demo

See output.

http://localhost:8080/Struts2Example/Image/Display.action

struts2 dynamic image demo

Download Source Code

Download It – Struts2-Dynamic-Image-Example.zip (26kb)

References

  1. Struts2 display dynamic image as array of bytes
  2. image servlet example
  3. Struts2 URL tag example
  4. Convert image to bytes of array in Java
  5. Struts2 stream result example

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Srinivas
Guest
Srinivas

Mkyong, Thanks for the worderful article, how do you cache <img src=" ” /> and image generated by the action, we want to cache images for performance. thanks

Nancy
Guest
Nancy
Am getting images from the database and storing all the images in a filepath( request.getSession().getServletContext().getRealPath). Now am having all the images in the filepath. Then am getting the images from filepath to private File[] filelist; Now am trying to display the filelist in JSP: <img src="“/> Output in browser is am getting the filepath of all the images(i can iterate) but images are not loading. If i put the tag in and click on the link its displaying “The address wasn’t understood”.If i enter the link the slash “/” is changing and the image in displaying. <a href="“/> <img src="“/>… Read more »
Pranshu
Guest
Pranshu

i am getting this error plz help also why do we need display action
my email : pranshushrivastava20@gmail.com

javax.imageio.IIOException: Can’t read input file!

at javax.imageio.ImageIO.read(ImageIO.java:1301)

at controller.ShowImage.getCustomImageInBytes(ShowImage.java:93)

at controller.CustomImageBytesResult.execute(CustomImageBytesResult.java:24)

SKR
Guest
SKR

Thanx for this example

can u plz tell me how to pick multiple image from database using struts 2

Saran
Guest
Saran

Thanks for the examples

can u tell How to do this application in springMVC

what is the spring tag used to display image like the tag (” “) used in struts.

Thanks

Nirmal
Guest
Nirmal

Hi,
i need to upload the image in one Jsp and have to display it in another jsp through struts2 action.

mats
Guest
mats

whenever I need some initial input for a new idea I might have and I google it you’re allways among the top 5 links and I allways know it will be helpful to check it out. you’re doing good work.

cheers
mats

Claudiu
Guest
Claudiu

Agree, great job! Excellent blog!!!!

brahmareddy
Guest
brahmareddy

display image by storing the server is good but the major problem is storing image and displaying image into database.
i have done storing image into data base using struts
but by retrieving it’s coming as a stream or
based o the parameter we used.
can anyone help me how to retrieve image from database and display on jsp.

g_07
Guest
g_07

thanks but not sure why it’s not working for me. i debug the project but it doesn’t seem to trigger the ImageAction class at all.

also the page display without error only not showing any images. any help would be great.

Wade
Guest
Wade

hi, there’s problem when i’m doing my own experiment according your
i’m using convention plugin-in so i configured like this
@Results({
@Result(name=”inputFile”, type=”imageResult”)
})

but got a error. The Result type [common.util.CustomizeStreamResult] which is defined in the Result annotation on the class [class action.CustomizeResultTypeAction] or determined by the file extension or is the default result type for the PackageConfig of the action, could not be found as a result-type defined for the Struts/XWork package [action#convention-default#] – [unknown location]

could you tell me where’s the problem?

Thank you!

janice
Guest
janice

Hi,

Thanks for the examples, they are great!

I am trying to implement you example into my website, reason, there are some jars missing in the download example. I was able to incorporate the example into my website, yet I am getting an error ‘404 error’. In the struts.xml file, I have used your package and namespace =”/Image”, but still getting ‘404 error’? I would think that struts.xml file is the only place to tell the server where to look for the jsp and action associated?

J

Thibaut
Guest
Thibaut

Thank you for sharing.

When I compile, I have the following error:

There is no result type defined for type ‘imageResult’ mapped with name ‘success’. Did you mean ‘imageResult’?

Do you have any ideas to solve this problem?

Thank you.