Java 通過url響應圖片


@ApiOperation(value = "海報圖片", httpMethod = "GET", response = Poster.class, notes = "query")
    @RequestMapping(path = "/posterImage", method = RequestMethod.GET)
    public void posterImage(@ApiParam("圖片地址") @RequestParam String imgUrl, HttpServletResponse response) throws Exception {
        log.info(">>>> Method:history>>posterImage request:{}", imgUrl);

        try {
            //new一個URL對象
            URL url = new URL(imgUrl);
            //打開鏈接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //設置請求方式為"GET"
            conn.setRequestMethod("GET");
            //超時響應時間為5秒
            conn.setConnectTimeout(5 * 1000);
            //通過輸入流獲取圖片數據
            InputStream inStream = conn.getInputStream();
            //得到圖片的二進制數據,以二進制封裝得到數據,具有通用性
            BufferedImage img = ImageIO.read(inStream);
            if (img != null) {
                String format = imgUrl.substring(imgUrl.lastIndexOf(".") + 1);
                ImageIO.write(img, format, response.getOutputStream());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM