JSP如何缩放图像?

5

有没有办法在JSP页面中缩放图像并显示?当检索和显示图像时,我想以相同的大小显示所有照片。是否有任何API可以做到这一点?我已经从Google搜索过了,但是我找到的都是关于使用工具包缩放图像的内容,但在Web应用程序中无法使用。

2个回答

4
您可以使用内置的Java 2D API来实现此功能(基本的Sun教程在此处)。
基本上,您需要创建一个Servlet,该Servlet在doGet()方法中获取原始图像的InputStream,将其通过Java 2D API传递,然后将其写入HTTP响应的OutputStream。然后,您只需将此Servlet映射到web.xml中的某个url-pattern,例如/thumbs/*,并在HTML <img>元素的src属性中调用此Servlet。
这是一个基本的启动示例(您仍然需要按照自己的方式处理意外情况):
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 密集型) 的任务,请记住这一点。您可能需要考虑自行缓存或预生成缩略图。


我也遇到了同样的问题,图像边框只在Excel中显示。有什么想法吗?在指定w和h参数之前,该图像可以显示,但没有指定大小。 - Palani

0
注意:仅使用JSP无法完成此任务,因为它是一种视图技术,不适合此任务。
从技术上讲,您可以这样做,但确实不建议这样做。
是的,我会将图像缓存长时间保存,并与原始图像的更改标识符一起保存,然后仅在原始图像更改(或缓存过期,可能是上次访问图像后一周)时重新创建调整大小的图像。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接