1. 程式人生 > 其它 >Java通過圖片的URL獲取圖片的寬高

Java通過圖片的URL獲取圖片的寬高

/**
     * 讀取遠端url圖片,得到寬高
     * @param imgurl 圖片路徑
     * @return [0] 寬  [1]高
     */
    public static int[] getImgWH(String imgurl) {
        boolean b=false;
        try {
            //例項化url
            URL url = new URL(imgurl);
            //載入圖片到輸入流
            java.io.BufferedInputStream bis = new
BufferedInputStream(url.openStream()); //例項化儲存位元組陣列 byte[] bytes = new byte[100]; //設定寫入路徑以及圖片名稱 OutputStream bos = new FileOutputStream(new File("pic.jpg")); int len; while ((len = bis.read(bytes)) > 0) { bos.write(bytes,
0, len); } bis.close(); bos.flush(); bos.close(); //關閉輸出流 b=true; } catch (Exception e) { //如果圖片未找到 b=false; } int[] a = new int[2]; if(b){//圖片存在 //得到檔案 java.io.File file = new
java.io.File("pic.jpg"); BufferedImage bi = null; boolean imgwrong=false; try { //讀取圖片 bi = javax.imageio.ImageIO.read(file); try{ //判斷檔案圖片是否能正常顯示,有些圖片編碼不正確 int i = bi.getType(); imgwrong=true; }catch(Exception e){ imgwrong=false; } } catch (IOException ex) { ex.printStackTrace(); } if(imgwrong){ a[0] = bi.getWidth(); //獲得 寬度 a[1] = bi.getHeight(); //獲得 高度 }else{ a=null; } //刪除檔案 file.delete(); }else{//圖片不存在 a=null; } return a; }
//使用
int
[] arr = getImgWH("imgUrl"); width = arr[0]; height = arr[1];