使用s:graphicImageDynamic组件,要有tomahawk-sandbox的jar包,我使用的是tomahawk-sandbox-1.1.6-SNAPSHOT.jar 。
JSF代码:
<%@ taglib uri="http://myfaces.apache.org/sandbox" prefix="s"%>
...
<s:graphicImageDynamic height="32" width="32" imageRendererClass="#{gmShowImageBean.imageRendererClass}" >
<f:param value="#{info.imageId}" name="imageId"/>
</s:graphicImageDynamic>
<s:graphicImageDynamic/>组件允许使用<f:param进行传值,#{info.imageId}是循环对象的主键,通过"imageId"名称传到request中,接在ImageRenderer类中获取,然后查询数据库得到image对象,从而进行渲染图片内容。
#{gmShowImageBean.imageRendererClass}这是返回渲染图片的Render类,gmShowImageBean类中代码如下:
public Class getImageRendererClass(){
return ImageRendererImpl.class;
}
Java代码:
public class ImageRendererImpl implements ImageRenderer {//必须实现ImageRenderer接口
private static final Log logger = LogFactory.getLog(ImageRendererImpl.class);
private byte[] image=null;
private int imageLength=0;
private String imageType="image/jpeg";
public void setContext(FacesContext facesContext, ResourceContext imageContext) throws Exception
{
//1.获取showImageBean,进而得到showImaeBean中注入的uploadservice,此service是用于根据imageId主键查询返回image对象
ShowImageBean imageBean = (ShowImageBean)facesContext.getApplication().getVariableResolver().resolveVariable(facesContext, "gmShowImageBean");
if(imageBean!=null){
//得到uploadService
UploadService uploadService = imageBean.getUploadService();
if(uploadService!=null){
//从request中获取<f:param传进来的"imageId"变量
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
Long imageId=Long.valueOf(request.getParameter("imageId") );
//根据ImageId主键查询数据库,返回uploadImage,这是图片的bo类,对图片的属性进行一个简单的封装
UploadImage uploadImage=uploadService.getUploadImage(imageId);
if(uploadImage!=null){
if(uploadImage.getFile()!=null && uploadImage.getFileType()!=null){
imageLength=uploadImage.getFile().length;//返回字节数组的长度
imageType=uploadImage.getFileType();//返回图片的类型
image=uploadImage.getFile(); //返回图片的字节数组
}
}else{
logger.error(LogUtil.msg("uploadImage is null!"));
}
}//if
}
}
/**
* @see org.apache.myfaces.custom.graphicimagedynamic.ImageRenderer#getContentLength()
*/
public int getContentLength() {
return imageLength;
}
/**
* @see org.apache.myfaces.custom.graphicimagedynamic.ImageRenderer#getContentType()
*/
public String getContentType()
{
return imageType;
}
/**
* @see org.apache.myfaces.custom.graphicimagedynamic.ImageRenderer # renderImage()
*/
public void renderResource(ResponseStream out)
throws IOException{
InputStream is = new ByteArrayInputStream(image);
try
{
byte[] buffer = new byte[1024];
int len = is.read(buffer);
while (len != -1)
{
out.write(buffer, 0, len);
len = is.read(buffer);
}
}finally{
is.close();
}
}
}
UploadImage类代码如下:
public class UploadImage implements Serializable {
private Long id;//主键ID
private byte[] file;//图片字节数组
private String fileType;//图片类型
private String fileName;//图片名称
private Long fileSize;//图片大小(单位K)
private Date uploadTime;//上传时间
....//省略get/set方法
}