gpt4 book ai didi

java - 使用 Picasso 将图像加载到位图中

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:02:42 24 4
gpt4 key购买 nike

我正在尝试使用 Picasso 库将图像从 URL 加载到位图中,但我发现的大多数示例都涉及将位图加载到 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); 似乎不正确,因为我收到了方法调用预期错误。

最佳答案

看起来您没有正确创建位图,但如果我处在您的位置,我会像这样创建缩放位图:

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 Adapter)中,如下所示:

Picasso.with(mContext)
.load("image url")
.into(mImageView);

关于java - 使用 Picasso 将图像加载到位图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32555794/

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