加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – JSP如何缩放图像?

发布时间:2020-12-14 19:11:17 所属栏目:Java 来源:网络整理
导读:无论如何缩放图像然后在jsp页面中显示?检索并显示图像时,我想显示所有相同尺寸的照片.是否有任何API可以做到这一点?我从谷歌搜索过,我发现的是关于使用takeit缩放图像,但无法在Web应用程序中使用. 最佳答案 你可以使用内置的Java 2D API(基本的Sun教程here

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

最佳答案
你可以使用内置的Java 2D API(基本的Sun教程here).

基本上,您需要创建一个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,thumbWidth,thumbHeight);
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    graphics2D.drawImage(image,null);

    // Write the image as JPG to the response along with correct content type.
    response.setContentType("image/jpeg");
    ImageIO.write(thumb,"JPG",response.getOutputStream());
}

使用web.xml映射的servlet如下:

这可以使用如下:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读