/** * 讀取遠程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];