站在巨人的肩膀上
private final int MAX_PIC_LENGTH = 200000;// 最大字节长度限制[可调,最好不要超过200000]
private final int SAMPLE_SIZE = 14;// 裁剪图片比列(1/14)[可调]
/**
* 获取网络图片
*/
private Bitmap getHttpBitmap(String imgUrl) throws Exception
{
URL htmlUrl = new URL(imgUrl);
URLConnection connection = htmlUrl.openConnection();
HttpURLConnection conn = (HttpURLConnection) connection;
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK)
{
InputStream inputStream = conn.getInputStream();
byte[] bytes = changeToBytes(inputStream);
if(bytes.length < MAX_PIC_LENGTH)
{
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
else if(bytes.length < MAX_PIC_LENGTH * SAMPLE_SIZE)
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize = SAMPLE_SIZE;
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
}
}
return null;
}
/**
* 将流转换成字节数组
*/
public byte[] changeToBytes(InputStream inputStream) throws Exception
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];// 每次读取的字节长度
int len = 0;
while((len = inputStream.read(buffer)) != -1)
{
outputStream.write(buffer, 0, len);
}
inputStream.close();
return outputStream.toByteArray();
}