有没有办法在JSP页面中缩放图像并显示?当检索和显示图像时,我想以相同的大小显示所有照片。是否有任何API可以做到这一点?我已经从Google搜索过了,但是我找到的都是关于使用工具包缩放图像的内容,但在Web应用程序中无法使用。
有没有办法在JSP页面中缩放图像并显示?当检索和显示图像时,我想以相同的大小显示所有照片。是否有任何API可以做到这一点?我已经从Google搜索过了,但是我找到的都是关于使用工具包缩放图像的内容,但在Web应用程序中无法使用。
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 密集型) 的任务,请记住这一点。您可能需要考虑自行缓存或预生成缩略图。