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

时间:2015-09-14 00:16:56

标签: java android picasso

我想使用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);似乎不正确,因为我得到一个方法调用预期错误。

1 个答案:

答案 0 :(得分:2)

看起来你没有正确创建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);