[英]Using Picasso to load an image into a bitmap
我想使用Picasso庫將URL中的圖像加載到Bitmap中,但我發現的大多數示例都是指將Bitmap加載到ImageView或類似的東西。
根據文檔,代碼應該是這樣的。
public void loadImage() {
Picasso.with(getBaseContext()).load("image url").into(new Target() {
@Override
public void onPrepareLoad(Drawable arg0) {
}
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom arg1) {
Bitmap bitImage = Bitmap(getApplicationContext(),bitmap);
}
@Override
public void onBitmapFailed(Drawable arg0) {
}
});
}
但Bitmap bitImage = Bitmap(getApplicationContext(),bitmap);
似乎不正確,因為我得到一個方法調用預期錯誤。
看起來你沒有正確創建Bitmap,但是如果我在你的位置,我會像這樣創建一個縮放的位圖:
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
bm, 0, 0, width, height, matrix, false);
bm.recycle();
return resizedBitmap;
}
然后將其設置為imageView,如下所示:
mImg.setImageBitmap(img);
整體而言,它看起來像這樣:
public void loadImage() {
Picasso.with(getBaseContext()).load("image url").into(new Target() {
// ....
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom arg1) {
// Pick arbitrary values for width and height
Bitmap resizedBitmap = getResizedBitmap(bitmap, newWidth, newHeight);
mImageView.setBitmap(resizedBitmap);
}
// ....
});
}
}
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
bm, 0, 0, width, height, matrix, false);
bm.recycle();
return resizedBitmap;
}
但我總是質疑你使用Target
,通常是一個非常專業的案例。 你應該在你將要顯示圖像的同一個班級中調用Picasso
的單身人士。 通常這是在Adapter
(也許RecyclerView適配器),如下所示:
Picasso.with(mContext)
.load("image url")
.into(mImageView);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.