无论如何缩放图像然后显示在jsp页面中?检索和显示图像时,我想以相同大小显示所有照片。有什么API可以做到吗?我从谷歌搜索,我发现那些是关于使用 takeit 缩放图像但不能在 Web 应用程序中工作。
问问题
11995 次
2 回答
4
您可以为此使用内置的Java 2D API(这里是 Sun 的基本教程)。
基本上,您需要创建一个Servlet,它在方法中获取InputStream
原始图像doGet()
,通过 Java 2D API 将其传递,然后将其写入OutputStream
HTTP 响应。然后你只需将这个 Servlet 映射到某个url-pattern
in 上web.xml
,例如,并在 HTML元素的属性中/thumbs/*
调用这个 Servlet 。src
<img>
这是一个基本的启动示例(您仍然需要按照自己的方式处理意外情况):
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// First get image file name as request pathinfo (or parameter, whatever you want).
String imageFilename = request.getPathInfo().substring(1);
// And get the thumbnail dimensions as request parameters as well.
int thumbWidth = Integer.parseInt(request.getParameter("w"));
int thumbHeight = Integer.parseInt(request.getParameter("h"));
// Then get an InputStream of image from for example local disk file system.
InputStream imageInput = new FileInputStream(new File("/images", imageFilename));
// Now scale the image using Java 2D API to the desired thumb size.
Image image = ImageIO.read(imageInput);
BufferedImage thumb = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = thumb.createGraphics();
graphics2D.setBackground(Color.WHITE);
graphics2D.setPaint(Color.WHITE);
graphics2D.fillRect(0, 0, thumbWidth, thumbHeight);
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
// Write the image as JPG to the response along with correct content type.
response.setContentType("image/jpeg");
ImageIO.write(thumb, "JPG", response.getOutputStream());
}
servlet 映射web.xml
如下:
<servlet>
<servlet-name>thumbServlet</servlet-name>
<servlet-class>com.example.ThumbServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>thumbServlet</servlet-name>
<url-pattern>/thumbs/*</url-pattern>
</servlet-mapping>
这可以按如下方式使用:
<img src="thumbs/filename.jpg?w=100&h=100" width="100" height="100">
注意:不,这不能单独使用 JSP 完成,因为它是一种不适合此任务的视图技术。
注意 2:这是一项非常昂贵(CPU 密集型)的任务,请记住这一点。您可能需要考虑自己预先缓存或预生成拇指。
于 2010-05-30T13:12:53.270 回答
0
注意:不,这不能单独使用 JSP 完成,因为它是一种不适合此任务的视图技术。
从技术上讲,您可以做到,但实际上这不是可取的。
是的,我会缓存图像很长时间,以及识别原始更改的内容,然后仅在原始更改时重新创建调整大小的图像(或者缓存过期,可能在最后一次访问图像一周后) .
于 2010-05-31T12:40:53.050 回答