栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JSP如何缩放图像?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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="https://www.mshxw.com/skin/sinaskin/image/nopic.gif" width="100" height="100">

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


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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/425703.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号