In this blog,
We are going to tell you how to cure the out of memory issue while loading the images in Picasso library using transform and resize methods.
If you want to resize the image with aspect ratio and avoid to OOM error then you can use the transform method of Picasso.
How to use Transform method
1 2 3 4 |
Picasso.with(this).load(imageURL) .transform(new BitmapTransform(MAX_WIDTH, MAX_HEIGHT)) .placeholder(R.drawable.placeholder) .into(imageView); |
BitmapTransform
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
public class BitmapTransform implements Transformation { int maxWidth; int maxHeight; public BitmapTransform(int maxWidth, int maxHeight) { this.maxWidth = maxWidth; this.maxHeight = maxHeight; } @Override public Bitmap transform(Bitmap source) { int targetWidth, targetHeight; double aspectRatio; if (source.getWidth() > source.getHeight()) { targetWidth = maxWidth; aspectRatio = (double) source.getHeight() / (double) source.getWidth(); targetHeight = (int) (targetWidth * aspectRatio); } else { targetHeight = maxHeight; aspectRatio = (double) source.getWidth() / (double) source.getHeight(); targetWidth = (int) (targetHeight * aspectRatio); } Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false); if (result != source) { source.recycle(); } return result; } @Override public String key() { return maxWidth + "x" + maxHeight; } }; |
How to use resize method
Transform images to properly adjust into layouts and to overcome the memory.
1 2 3 4 5 |
Picasso.with(this) .load(imageURL) .resize(500, 500) .centerCrop() .into(imageView) |
centerCrop
– Scale the image venerate the aspect ratio until it fills the size.
Crop either the top and bottom or left and right so it matches the size exactly.