1邢羔、獲取本地圖片的的字節(jié)數(shù)
/**
* 獲取本地圖片的字節(jié)數(shù)
* @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);
}
/**
* 將獲取到的字節(jié)數(shù)轉(zhuǎn)換為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);
}
測(cè)試結(jié)果
原始圖片的大小
2、獲取網(wǎng)絡(luò)圖片地址的字節(jié)數(shù)
/**
* 根據(jù)圖片地址獲取圖片信息
* @param urlPath 網(wǎng)絡(luò)圖片地址
* @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;
}
/**
* 將流轉(zhuǎn)換為字節(jié)
* @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;
}
測(cè)試結(jié)果
查看源碼
鏈接: https://pan.baidu.com/s/1GhrX2WIlwPqPQ9DhlC786w 提取碼: v854