2010-05-30 114 views
5

無論如何縮放圖像,然後顯示在jsp頁面?當檢索並顯示圖像時,我想以相同尺寸顯示所有照片。有沒有什麼API可以做到這一點?我從谷歌搜索,我發現的是通過使用takeit縮放圖像,但不能在web應用程序中工作。JSP如何縮放圖像?

回答

4

你可以使用內建的Java 2D API這個(基本的太陽教程here)。

基本上,需要創建一個Servlet它獲取的原始圖像的InputStreamdoGet()方法,通過Java 2D API傳遞給它,然後將其寫入到HTTP響應的OutputStream。然後,您只需在web.xml的某個url-pattern上映射此Servlet,例如, /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()); 
} 

隨着web.xml映射在servlet如下:

<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密集型)任務,請記住這一點。您可能需要考慮自行緩存或預先生成拇指。

+0

我也是這樣做的,圖片邊框只顯示在excel中。任何想法?僅供參考之前我指定的W和H參數圖像顯示,但沒有指定的大小。 – Palani 2011-11-22 06:08:19

0

注:不,這不能與JSP 獨自完成,因爲它是一個視圖技術 不適合這項任務。

從技術上講,你可以做到這一點,但事實上這不是可取的。

是的,我會將圖像緩存很長一段時間,連同一些東西來識別對原始的更改,然後只有在原始更改(或緩存過期,也許是圖像後一週)時重新創建已調整大小的圖像最後訪問)。