1. 程式人生 > 其它 >從專案路徑下讀取圖片返回到瀏覽器

從專案路徑下讀取圖片返回到瀏覽器

讀取圖片程式碼:

  /**
     * 獲取圖片。
     * http://localhost:88/api/lexueManager/photo/load/48c3df11ca5f4c80bab198159e41a5de.png
     * 得到專案路徑下 /file/photo/48c3df11ca5f4c80bab198159e41a5de.png的圖片
     */
    @LoginRequired
    @RequestMapping("/load/{name}")
    public void loadPhoto(HttpServletResponse response,@PathVariable("name") String name) {
        String photoPath = null;

        try {
            //得到專案中圖片儲存的路徑
            photoPath = new File("").getCanonicalPath() + File.separator + "lexue"
                    + File.separator + "file" + File.separator + "photo";
        } catch (IOException e) {
            throw new RuntimeException("獲取專案路徑失敗", e);
        }
        photoPath += File.separator + name;


        //將一個圖片載入到記憶體
        BufferedImage image = null;
        try {
            image = ImageIO.read(new FileInputStream(photoPath));
        } catch (IOException e) {
            throw new RuntimeException("把圖片載入到記憶體失敗", e);
        }

        // 將圖片輸出給瀏覽器
        response.setContentType("image/png");//宣告返回的是png格式的圖片。
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
            //不用關閉這個流,spring會自動幫我們關閉這個流。
        } catch (IOException e) {
            throw new RuntimeException("響應圖片失敗,伺服器發生異常!", e);
        }
    }

postman測試:

核心方法

把圖片載入到記憶體:

image = ImageIO.read(new FileInputStream(photoPath));

把圖片傳輸給瀏覽器:

// 將圖片輸出給瀏覽器
response.setContentType("image/png");//宣告返回的是png格式的圖片。
try {
    OutputStream os = response.getOutputStream();
    ImageIO.write(image, "png", os);
    //不用關閉這個流,spring會自動幫我們關閉這個流。
} catch (IOException e) {
    throw new RuntimeException("響應圖片失敗,伺服器發生異常!", e);
}

本文來自部落格園,作者:五行缺知識,轉載請註明原文連結:https://www.cnblogs.com/wyw123456/p/15650995.html