JSP如何缩放图像?

JSP如何缩放图像?,第1张

JSP如何缩放图像

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

基本上,您需要创建一个Servlet,该Servlet获取方法

InputStream
中的原始图像
doGet()
,将其传递给Java 2D
API,然后将其写入
OutputStream
HTTP响应的。然后你只需映射这个servlet上有一定
url-pattern
web.xml
,例如
/thumbs/*
在呼叫这个servlet
src
的HTML属性
<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="http://www.kaotop.com/skin/sinaskin/image/nopic.gif" width="100" height="100">

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


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



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5082523.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-16
下一篇2022-11-16

发表评论

登录后才能评论

评论列表(0条)

    保存