Using Picasso to load an image into a bitmap

I am loading an image from a URL into a bitmap using the Picasso library, but most of the examples I found relate to loading Bitmap into ImageView or something similar.

According to the documentation, the code should be something like this.

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) { } }); } 

But Bitmap bitImage = Bitmap(getApplicationContext(),bitmap); doesn't seem to be correct, since I get the expected method error.

+5
source share
1 answer

It looks like you did not create the bitmap correctly, but if I were in your position, I would create a scaled 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; } 

Then install it in the image as follows:

 mImg.setImageBitmap(img); 

In general, it will look like this:

 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; } 

But I doubt that you use Target at all, usually for a highly specialized case. You must call singleton from Picasso in the same class as you will display the images. Usually this is in the Adapter (possibly the RecyclerView adapter):

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

All Articles