[英]Get Bitmap from an URL
我正在嘗試從 URL 獲取位圖圖像。
(示例: https : //cdn.bulbagarden.net/upload/9/9a/Spr_7s_001.png )
但是connection.connect()
行似乎存在問題,我無法弄清楚。
我已允許在應用程序中訪問互聯網。
public static Bitmap getBitmapFromURL(String src) {
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
URL url = new URL(src);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();
}
return BitmapFactory.decodeStream(inputStream);
}
您可以使用 glide 作為一個簡短的解決方案
implementation "com.github.bumptech.glide:glide:4.11.0"
annotationProcessor "com.github.bumptech.glide:compiler:4.11.0"
try {
Bitmap bitmap = Glide
.with(context)
.asBitmap()
.load(imageUrl)
.submit()
.get();
} catch (Exception e) {
e.printStackTrace();
}
一般網絡連接應該是一個單獨的線程來完成的。 您可以為此使用AsyncTask
。 例如,這有效:
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_layout);
imageView = (ImageView) findViewById(R.id.imageView);
new LoadImage().execute("https://cdn.bulbagarden.net/upload/9/9a/Spr_7s_001.png");
}
private class LoadImage extends AsyncTask<String, Void, Bitmap>{
@Override
protected Bitmap doInBackground(String... strings) {
Bitmap bitmap = null;
try {
InputStream inputStream = new URL(strings[0]).openStream();
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.