What is Picasso Library?
A powerful image downloading and caching Library for Android. By its use Developer, to load an image in “android application” with one line of code, without worry about caching, transformation and threading an image to load.
- Picasso usage ARGB- 8888 Bitmap format, so it gives smooth images.
- Picasso loading image process, first checks in the cache, after disk and then network .
- Picasso attempts 3 times to load an image into image view.
Syntax:
1 |
Picasso.with(this).load(url).into(imageview); |
where “this” is Activity object, “url” is image address URL (source) and “imageview” is ImageView (destination).
Picasso methods –
- resize(width, height), use for resizing an image.
- onlyScaleDown(), use with resize() method when small image not to resize.
- centerInside(), use for, when an image not fills the bounds of ImageView.
- fit(), when ImageView is well defined in size then it resizes the image to ImageView width and height.
- centerInCrop(), use for, when an image fills the bounds of ImageView.
memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE) ,
NO_CACHE-
Skips memory cache lookup when processing a request.
NO_STORE-
Skips storing the final result into the memory cache. Useful for one-off requests to avoid evicting other bitmaps from the cache (it is needed, when loads an image only once).
Out of memory Exception : It happened when loading large size images . So, it solved by resizing the images. if we use resize(width, height) then the image is not resized as the aspect ratio. So we use a custom transform class using transform() method.
Example.
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 39 40 41 |
public class BitmapTransform implements Transformation { int maxWidth; int maxHeight; public BitmapTransform(){ super(); } 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; } } |
1 2 3 4 5 6 7 8 |
Picasso.with(mContext) .load(url) .placeholder(R.drawable.placeholder) // .resize(width, height) .transform(new BitmapTransform(width, height)) // .rotate(degree) .into(imageView); } |