我正在寻求一些重构一些代码的帮助。我有这些获取位图的方法,它们执行类似的操作,将输入流解码为位图。我必须在 try/catch 中包围输入流的开头,并在末尾添加一个finally。我注意到这些方法有很多共同点,我想重构它,所以我只需要编写一次 try/catch 。
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;
}
最佳答案
尝试滑行或毕加索。
我正在使用滑行。链接在这里https://github.com/bumptech/glide
并查看https://github.com/bumptech/glide/wiki更多信息。
//from glide document
public void onCreate(Bundle savedInstanceState) {
...
ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
Glide.with(this).load("http://goo.gl/gEgYUd").into(imageView);
}
关于android - 简化从 Uri/Url 获取位图的过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32043620/