gpt4 book ai didi

android - 简化从 Uri/Url 获取位图

转载 作者:行者123 更新时间:2023-11-29 00:08:29 25 4
gpt4 key购买 nike

我正在寻找重构一些代码的帮助。我有这些获取位图的方法,它们在将输入流解码为位图时做类似的事情。我必须在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com