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

Ale*_*lex 5 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) {
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

但Bitmap bitImage = Bitmap(getApplicationContext(),bitmap);似乎不正确,因为我得到一个方法调用预期错误.

And*_*oid 2

看来您没有正确创建位图,但如果我处于您的位置,我会创建一个缩放的位图,如下所示:

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;
}
Run Code Online (Sandbox Code Playgroud)

然后将其设置为 imageView,如下所示:

mImg.setImageBitmap(img);
Run Code Online (Sandbox Code Playgroud)

总的来说,它看起来像这样:

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;
}
Run Code Online (Sandbox Code Playgroud)

但我质疑你Target是否完全使用,通常是针对非常特殊的情况。您应该在Picasso将显示图像的同一类中调用单例。通常这是在Adapter(可能是 RecyclerView 适配器)中,如下所示:

Picasso.with(mContext)
    .load("image url")
    .into(mImageView);
Run Code Online (Sandbox Code Playgroud)