java根據圖片地址獲取圖片的位元組數
1、獲取本地圖片的的位元組數
/** * 獲取本地圖片的位元組數 * @param imgPath * @return */ public static String pathSize(String imgPath) { File file = new File(imgPath); FileInputStream fis; int fileLen = 0; try { fis = new FileInputStream(file); fileLen = fis.available(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bytes2kb(fileLen); } /** * 將獲取到的位元組數轉換為KB,MB模式 * @param bytes * @return */ public static String bytes2kb(long bytes){ BigDecimal filesize = new BigDecimal(bytes); BigDecimal megabyte = new BigDecimal(1024 * 1024); float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP).floatValue(); if(returnValue > 1) return (returnValue + "MB"); BigDecimal kilobyte = new BigDecimal(1024); returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP).floatValue(); return (returnValue + "KB"); } public static void main(String[] args) { String imgUrl="E:\\vacations.ctrip.com_852377.4201748744.jpg"; String pathSize = pathSize(imgUrl); System.out.println("獲取到圖片的大小: " + pathSize); }
測試結果

測試.png
原始圖片的大小

原始圖片.png
2、獲取網路圖片地址的位元組數
/** * 根據圖片地址獲取圖片資訊 * @param urlPath網路圖片地址 * @return */ public static byte[] getImageFromURL(String urlPath) { byte[] data = null; InputStream is = null; HttpURLConnection conn = null; try { URL url = new URL(urlPath); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setRequestMethod("GET"); conn.setConnectTimeout(6000); is = conn.getInputStream(); if (conn.getResponseCode() == 200) { data = readInputStream(is); } else{ data=null; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(is != null){ is.close(); } } catch (IOException e) { e.printStackTrace(); } conn.disconnect(); } return data; } /** * 將流轉換為位元組 * @param is * @return */ public static byte[] readInputStream(InputStream is) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length = -1; try { while ((length = is.read(buffer)) != -1) { baos.write(buffer, 0, length); } baos.flush(); } catch (IOException e) { e.printStackTrace(); } byte[] data = baos.toByteArray(); try { is.close(); baos.close(); } catch (IOException e) { e.printStackTrace(); } return data; }
測試結果

測試.png
檢視原始碼
連結: https://pan.baidu.com/s/1GhrX2WIlwPqPQ9DhlC786w 提取碼: v854