JSP如何缩放图像?

use*_*501 5 java jsp servlets image-scaling

无论如何缩放图像然后在jsp页面中显示?检索并显示图像时,我想显示所有相同尺寸的照片.是否有任何API可以做到这一点?我从谷歌搜索过,我发现的是关于使用takeit缩放图像,但无法在Web应用程序中使用.

Bal*_*usC 4

为此,您可以使用内置的Java 2D API (这里是基本的 Sun 教程)。

基本上,您需要创建一个Servlet,它在方法中获取InputStream原始图像doGet(),将其通过 Java 2D API 传递,然后将其写入OutputStreamHTTP 响应。然后,您只需将此 Servlet 映射到某个url-pattern位置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());
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

可以按如下方式使用:

<img src="thumbs/filename.jpg?w=100&h=100" width="100" height="100">
Run Code Online (Sandbox Code Playgroud)

注意:不,这不能单独使用 JSP 来完成,因为它是一种不适合此任务的视图技术。


注 2:这是一项相当昂贵的(CPU 密集型)任务,请记住这一点。您可能需要考虑自己预先缓存或预生成拇指。