Search code examples
androidandroid-layoutpicasso

Android round image with picasso


I would like to round the corner of image with 5px to show on imageview with Picasso. I have created simple class as ImageRoundCorners in which I am using simple method to round image corners, but my code is not working, corners are not rounded.Below is my code :

   file = new File(APP.DIR_APP + APP.IMAGE + "/ok.jpg");
   if (file.isFile() && file.exists()) {
       Uri uri = Uri.fromFile(file);
       Picasso.with(this).load(uri).transform(new ImageRoundCorners()).into(fiv_image_view);
   }

and ImageRoundCorners class:

import com.squareup.picasso.Transformation;

public class ImageRoundCorners implements Transformation {
    @Override
    public Bitmap transform(Bitmap source) {
        Bitmap output = Bitmap.createBitmap(source.getWidth(), source
                .getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int   color   = 0xff424242;
        final Paint paint   = new Paint();
        final Rect  rect    = new Rect(0, 0, source.getWidth(), source.getHeight());
        final RectF rectF   = new RectF(rect);
        final float roundPx = 50;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(source, rect, rect, paint);

        return output;
    }

    @Override
    public String key() {
        return "RoundImage";
    }
}

what is the problem in this code and how can i resolve that?

I am getting this error:

java.lang.IllegalStateException: Transformation RoundImage mutated input Bitmap but failed to recycle the original.

Solution

  • The error message is pretty clear. You simply forgot to recycle the original Bitmap.

    ....
    canvas.drawBitmap(source, rect, rect, paint);
    source.recycle();
    return output;
    

    Just one line missing from your code! (I'm amazed at all these answers telling you to do all sorts of unrelated, uprooting solutions.)