问题是这么来的,博主想获取一组图片,就开始学习网络图片的获取。
先贴上一段代码,博主就是用这段代码来世获取图片的:
//获取图片资源 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(); bitmap = BitmapFactory.decodeStream(is); return bitmap; }else{ return null; } } catch (Exception e) { e.printStackTrace(); } return null; }else{ return null; } }
不过问题就接着来了,多测试几下,你会发现出现了OutOfMemery的问题,内存溢出,毫无头绪,一百度,发现的答案导出了另外一个东西,叫做BitmapFactory.Options
这个参数可以设置图片的大小问题,把图片进行缩放,这样就做小了内存。
进过一翻折腾博主把代码修改成了如下:
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(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true;//此参数设置为true时,就只获取图片的长度和宽度,options.outWidth options.outHeight,就可以提取出数值 bitmap = BitmapFactory.decodeStream(is,null,options); options.outHeight = options.outHeight * options.outWidth/200; options.outWidth = 200; options.inSampleSize = options.outHeight/200;//这时你就可以设置此常数来调整缩放的比列,如设置为2,就是缩小成1/2。 options.inJustDecodeBounds = false;<span style="font-family: Arial, Helvetica, sans-serif;">//重新读入图片,注意这次要把options.inJustDecodeBounds 设为 false哦</span> options.inPreferredConfig = Bitmap.Config.ARGB_4444;// 默认是Bitmap.Config.ARGB_8888 options.inPurgeable = true; options.inInputShareable = true; bitmap = BitmapFactory.decodeStream(is,null,options);//此时重新读取 return bitmap; }else{ return null; } } catch (Exception e) { e.printStackTrace(); } return null; }else{ return null; } }
代码写完了,但发现返回的值是null;这是为什么呢,看了网上的例子一般都是获取的本地的图片,所以bitmap = BitmapFactory.decodeStream(is,null,options);采用的流用的是new FileInputStream(file);
问题就出在这里,由于我们的流是网络的流is,再经过一次的读取之后就变成了空,重新用bitmap = BitmapFactory.decodeStream(is,null,options);读取时自然就变成了null;
好了,既然发现了问题,那么我们的思路就是先把流保存下来变成字节流。