【发布时间】:2018-02-02 19:37:35
【问题描述】:
我正在尝试将图像从 URL 加载到位图,但出现 NetworkOnMainThreadException 错误,但我不知道为什么。
这是我正在使用的方法:
public Bitmap getBitmapFromURL(String src) {
try {
java.net.URL url = new java.net.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) {
e.printStackTrace();
return null;
}
}
我还尝试使用 Picasso 库将图像加载到 Target,因为最后,我想使用 Palette 从该图像中获取主色。这是我使用毕加索的代码:
Picasso.with(MovieDetails.this)
.load("https://image.tmdb.org/t/p/w500" + backdrop)
.into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Palette palette = Palette.from(bitmap).generate();
System.out.println(palette.getVibrantSwatch().toString().substring(16, Math.min(palette.getVibrantSwatch().toString().length(), 22)));
LinearLayout lLayout = (LinearLayout) findViewById(R.id.layout_bg);
lLayout.setBackgroundColor(Color.parseColor("#"+ palette.getVibrantSwatch().toString().substring(16, Math.min(palette.getVibrantSwatch().toString().length(), 22))));
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
我将它放在我的 onCreate 方法中,但是在所有三个 @Override 方法中都出现“方法没有覆盖其超类中的方法”错误。
【问题讨论】:
标签: android picasso android-bitmap loadimage