Android将图像从URL加载到位图对象中
我试图将图像从URL加载到位图对象中,但最终总是出现NetworkInUIThread类异常。有人能为我提供一个图书馆吗 请注意,我并不是想把图像放到ImageView中,我想先把它放到位图对象中,因为它以后会在我的应用程序中使用更多次 我在其他StackOverflow线程中发现了这段代码,但它不起作用Android将图像从URL加载到位图对象中,android,image,bitmap,Android,Image,Bitmap,我试图将图像从URL加载到位图对象中,但最终总是出现NetworkInUIThread类异常。有人能为我提供一个图书馆吗 请注意,我并不是想把图像放到ImageView中,我想先把它放到位图对象中,因为它以后会在我的应用程序中使用更多次 我在其他StackOverflow线程中发现了这段代码,但它不起作用 public static Bitmap getBitmapFromURL(String src){ try{ URL url = new URL(src);
public static Bitmap getBitmapFromURL(String src){
try{
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
}catch(IOException e){
return null;
}
}
试一试
试一试
您可以使用Glide从服务器下载图像并将其存储在位图对象中
Bitmap theBitmap = Glide.
with(this).
load("http://....").
asBitmap().
into(100, 100). // Width and height
get();
请参考此内容在应用程序中添加滑动依赖项->您可以使用滑动从服务器下载图像并将其存储在位图对象中
Bitmap theBitmap = Glide.
with(this).
load("http://....").
asBitmap().
into(100, 100). // Width and height
get();
请参考此内容在应用程序中添加滑动依赖项->将此代码放入
异步任务的doInBackground
方法中
e、 g
将此代码放入AsyncTask的doInBackground
方法中
e、 g
可能重复的可能重复的第一次尝试阅读关于NetworkOnMainThreadException
这将有助于开发可能重复的第一次尝试阅读关于NetworkOnMainThreadException
这将有助于开发无法使用最新GlideI解析方法“asBitmap”不希望在ImageView中加载图像无法使用最新的Glide解析方法“asBitmap”我不希望在ImageView中加载图像这会起作用,但我需要在我的活动中获取位图结果对象。这是在onPostExecute中必须做的事。。。在活动中创建MyAsyncTask作为内部类。阅读AsyncTask教程了解更多信息这将起作用,但我需要在活动中获取位图结果对象。这是在onPostExecute中必须执行的操作。。。在活动中创建MyAsyncTask作为内部类。有关更多信息,请阅读AsyncTask教程
Bitmap theBitmap = Glide.
with(this).
load("http://....").
asBitmap().
into(100, 100). // Width and height
get();
private class MyAsyncTask extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch(IOException e) {
return null;
}
}
protected void onPostExecute(Bitmap result) {
//do what you want with your bitmap result on the UI thread
}
}
new MyAsyncTask().execute(src);