2
我正在寻找一些帮助重构一些代码。我有这些获取位图的方法,他们在将输入流解码为位图时做了类似的操作。我必须在try/catch中结尾输入流的开头。我注意到这些方法有很多共同点,并且我想重构它,所以我只需要编写try/catch一次。简化从Uri/Url获取位图
public static Bitmap fromUri(@NonNull Context context, @NonNull Uri uri) {
InputStream inputStream = null;
try {
inputStream = context.getContentResolver().openInputStream(uri);
return BitmapFactory.decodeStream(inputStream, null, new BitmapFactory.Options());
} catch (FileNotFoundException e) {
return null;
} catch (NullPointerException e) {
return null;
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
// ignore
}
}
}
public static Bitmap fromURL(@NonNull String src, @Nullable BitmapFactory.Options options) {
InputStream inputStream = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(src);
HttpResponse response = httpClient.execute(request);
inputStream = response.getEntity().getContent();
return BitmapFactory.decodeStream(inputStream, null, options);
} catch (Exception e) {
return null;
} finally {
if (inputStream != null) {
try {
//todo test that input stream is closed
inputStream.close();
} catch (IOException e) {
// ignore
}
}
}
}
我想过写这样的东西,但我不确定它是否使它变得可读。任何建议,以改善这一点?
public static Bitmap fromUri(@NonNull Context context, @NonNull Uri uri) {
InputStream inputStream = getInputStream(context, uri);
return BitmapFactory.decodeStream(inputStream, null, new BitmapFactory.Options());
}
public static Bitmap fromURL(@NonNull String src, @Nullable BitmapFactory.Options options) {
InputStream inputStream = getInputStream(null, src);
return BitmapFactory.decodeStream(inputStream, null, options);
}
public static InputStream getInputStream(@Nullable Context context, @NonNull Object source){
InputStream inputStream = null;
try {
if(source instanceof String){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(String.valueOf(source));
HttpResponse response = httpClient.execute(request);
inputStream = response.getEntity().getContent();
} else if(source instanceof Uri){
inputStream = context.getContentResolver().openInputStream((Uri) source);
}
} catch (Exception e) {
return null;
} finally {
if (inputStream != null) {
try {
//todo test that input stream is closed
inputStream.close();
} catch (IOException e) {
// ignore
}
}
}
return inputStream;
}
感谢您的答案,我使用滑翔自己,但在这种情况下,我不需要加载到imageview。我需要直接访问位图 – Eoin
阅读这只是下载图像。 http://stackoverflow.com/questions/27640307/android-glide-how-to-download-and-cache-bitmaps。 – kfmes
这是好的,但唯一的问题是我还是要给出宽度和高度,但我不知道这些会是什么 – Eoin