其实不使用ImageIO,就是用一般的BufferedOutputStream+byte[] buffer也可以
关键在于通过response设置页面的MIME Type,自行Google~~~
源代码直接帖了。。。
ImageTag.java
public class ImageTag extends SimpleTagSupport { private String fileName; private HttpServletResponse response; private String imageType; public void setImageType(String imageType) { this.imageType = imageType; } public void setFileName(String fileName) { this.fileName = fileName; } public void setResponse(HttpServletResponse response) { this.response = response; } @Override public void doTag() throws JspException, IOException { response.setContentType("image/" + imageType); // This is necessary!!! BufferedImage image = null; BufferedOutputStream outputStream = null; try { File imageFile = new File(fileName); Image src = ImageIO.read(imageFile); int width = src.getWidth(null); int height = src.getHeight(null); image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); image.getGraphics().drawImage(src, 0, 0, width, height, null); outputStream = new BufferedOutputStream(response.getOutputStream()); ImageIO.write(image, imageType, outputStream); outputStream.flush(); // write the content from the buffer to the page } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (outputStream != null) outputStream.close(); } }}
tagext.tld
Tag extensions, my customized tag library. xxx ext tags 1.0 ext http://tags.xxx.com/ext Load the specified image file and display it on the page. image com.v1.ex120.ImageTag empty The file extension of the image file. imageType true true The URI of the image file on the disk. fileName true true The HttpServletResponse of the display page. Normally you'd use the response object of the page in which this tag is used. response true true
imagetag.jsp
<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%><%@ taglib uri="http://tags.xxx.com/ext" prefix="ext" %>Insert title here