上次我们提到要把网络图片的输入流先转成字节数组,这样就解决了内存溢出的问题
实现的代码如下:
//获取图片资源
public static Bitmap getBitmapImage(String path){
Bitmap bitmap = null;
if(!TextUtils.isEmpty(path)){
URL url = null;
try {
url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
int code = conn.getResponseCode();
if(code == 200){
InputStream is = conn.getInputStream();
byte[] data = getByteArray(is);//转换成字节数组
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
options.outHeight = options.outHeight * options.outWidth/200;
options.outWidth = 200;
options.inSampleSize = options.outHeight/200;
options.inJustDecodeBounds = false;//重新读入图片,注意这次要把options.inJustDecodeBounds 设为 false哦
options.inPreferredConfig = Bitmap.Config.ARGB_4444;// 默认是Bitmap.Config.ARGB_8888
options.inPurgeable = true;
options.inInputShareable = true;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
System.out.println(options.outWidth + " " + options.outHeight);
return bitmap;
}else{
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}else{
return null;
}
}
//转换输入流为字节流
public static byte[] getByteArray(InputStream is){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = 0;
try {
while((len = is.read(buf)) != -1){
outputStream.write(buf,0,len);
}
return outputStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
主要替换了实现语句为
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
这样就完美的解决了问题
备注:纯属本人学习笔记、积累知识、需要的随意看看。