Sunday 23 September 2012

Crop image in circular shape in android

Hello Friends,

Have you searching for cropping an image and convert it into circular shape ???
Following function will helps you to convert an image into circular shape.



Note: I am passing my image in bitmap format as a parameter in a function.

  /*
  * Making image in circular shape
  */
 public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
  // TODO Auto-generated method stub
  int targetWidth = 50;
  int targetHeight = 50;
  Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, 
                            targetHeight,Bitmap.Config.ARGB_8888);
  
                Canvas canvas = new Canvas(targetBitmap);
  Path path = new Path();
  path.addCircle(((float) targetWidth - 1) / 2,
  ((float) targetHeight - 1) / 2,
  (Math.min(((float) targetWidth), 
                ((float) targetHeight)) / 2),
          Path.Direction.CCW);
  
                canvas.clipPath(path);
  Bitmap sourceBitmap = scaleBitmapImage;
  canvas.drawBitmap(sourceBitmap, 
                                new Rect(0, 0, sourceBitmap.getWidth(),
    sourceBitmap.getHeight()), 
                                new Rect(0, 0, targetWidth,
    targetHeight), null);
  return targetBitmap;
 }


For providing border around your imageView :
   
    <ImageView
            android:id="@+id/imgView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/btnEdit"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="40dp"
            android:background="@drawable/rounded"
            android:adjustViewBounds="true"
            android:gravity="center"
            android:src="@drawable/happy"/>

Add this xml inside your drawable folder :

=>rounded.xml

<?xml version="1.0" encoding="utf-8"?>

    <solid android:color="@android:color/white" />

    <stroke
        android:width="3dip"
        android:color="#FF0000" />

    <corners android:radius="10dp" />
    <padding
        android:bottom="0dp"
        android:left="0dp"
        android:right="0dp"
        android:top="0dp" />

</shape>



Hope , this will helps anyone......
Enjoy Coding.... :)

Download Source Code

Mukesh Kumar

Hi Guys I am from Delhi working as Web/Mobile Application Developer(Android Developer), also have knowledge of Roboelctric and Mockito ,android test driven development... Blogging has been my passion and I think blogging is one of the powerful medium to share knowledge and ideas....

39 comments:

  1. thanks for code.. image is displayed in circular shape but precision is not so clear...

    ReplyDelete
  2. I Agreed that image is not clear .Sorry, I just forgot to update my answer.

    Try to use antialiasing and filterbitamp in your code. Try this code....an d let me know its work or not....

    Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight,
    Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(targetBitmap);
    Path path = new Path();
    path.addCircle(((float) targetWidth) / 2,
    ((float) targetHeight) / 2,
    (Math.min(((float) targetWidth), ((float) targetHeight)) / 2),
    Path.Direction.CW);
    Paint paint = new Paint();
    paint.setColor(Color.GRAY);
    //paint.setStyle(Paint.Style.STROKE);
    paint.setStyle(Paint.Style.FILL);
    paint.setAntiAlias(true);
    paint.setDither(true);
    paint.setFilterBitmap(true);
    canvas.drawOval(new RectF(0, 0, targetWidth, targetHeight), paint) ;
    //paint.setColor(Color.TRANSPARENT);
    canvas.clipPath(path);
    Bitmap sourceBitmap = scaleBitmapImage;
    canvas.drawBitmap(sourceBitmap, new Rect(0, 0, sourceBitmap.getWidth(),
    sourceBitmap.getHeight()), new RectF(0, 0, targetWidth,
    targetHeight), paint);

    ReplyDelete
  3. Hey Mukesh what a great code. Thanks a lot. Mukesh I need one more help if you can, I want to add 3dp round border with that. So could you please help me that How can I do it? I have done with your above example but need to give border as well.
    Thanks
    Gaurav

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Thanks Gaurav,
    You can add the 3dp round border across your image using "drawable". I am sharing my code in which I am doing the same thing.May be its helps you.....

    rounded.xml:










    And in my layout(xml) where I am using the imageview to show the rounded image with 3 dp border,I just set the backround from drawable.
    See the code:




    Let me know its helps you or not??

    ReplyDelete
  6. hey thanks for reply :) unfortunately I can't see you code. can I have it by email?

    gauravdarji1100@gmail.com

    Thanks,
    Gaurav

    ReplyDelete
  7. Yes Sure,
    Check your email.
    I have dropped an email with the code.

    ReplyDelete
  8. Hey thank you very much. :)

    Thanks,

    ReplyDelete
  9. Hey Mukesh Good morning. I need more help from you dear. I have implemented as per you code and it's work perfectly. But Mukesh How can I give that bitmap image height and weight in DP? I want that cropped images circular shape in "80*80 DP" ... so please could you please help me?

    Thanks,
    Gaurav

    ReplyDelete
  10. Hey , there is two way to achieve this:
    1. Using xml, simply provide the layout_height and layout_width as 80*80 dp Or
    2. Using java first find the id of imageview and then
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    params.width = 80;
    params.height = 80;
    imgView.setLayoutParams(params);

    In this way you can do it in java.

    ReplyDelete
  11. hey dear Mukesh, I have did something else. I have implemented method to get DP to pixel value.. and it work perfectly. :) See below code:

    public static int getDPEquivalentPixels(Context context, float dp){
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    int pixels = (int) (metrics.density * dp + 0.5f);
    return pixels;
    }

    ReplyDelete
  12. Thanx Gaurav, for sharing your code and I like the way you did.The another and good way to do this.

    thanks a lot...

    ReplyDelete
  13. Do you have codes in pure java? I have a bufferedimage and I want to make it into a circle shape

    ReplyDelete
  14. Hey Mukesh Thanks for your code but i cannot see the code for adding a 3 dp border around the circle (interior).Could you please update the answer so that it can be useful for others as well.

    ReplyDelete
  15. Hello Friends,

    Now check the code I just added the code for adding border around the image.

    ReplyDelete
  16. Hey Mukesh thanks for your quick replay.However the border visible now is a rectangular one.I needed some thing like this.If possible could you tell me how to achieve it.
    http://stackoverflow.com/questions/14050813/how-to-make-an-image-fit-into-a-circular-frame-in-android

    ReplyDelete
  17. hello, have you tried using "Oval" in xml, how its look like ?

    ReplyDelete
  18. Yes Mukesh I just replaced and checked.However after setting the image i cannot see the border i have used your above method getRoundedShape() and changed the targetWidth and targetHeight to 150 dp also tried using 50dp but still only the image is visible not the border around it.

    ReplyDelete
  19. Also using the above code gives me error
    Caused by: java.lang.OutOfMemoryError
    at android.graphics.Bitmap.nativeCreate(Native Method),at android.graphics.Bitmap.createBitmap(Bitmap.java:551),at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:437)

    ReplyDelete
  20. Do u have any idea Mukesh why am i encountering such a issue since my app crashes because of it?

    ReplyDelete
  21. HI,
    The out Of Memory error occur because of the large bitmap size, try to scale bitmap image and then crop.

    ReplyDelete
  22. Hi mukesh can u suggest me how will i go about it or provide some code since i do not know how much to scale it

    ReplyDelete
  23. Hey Bro,
    Great post I was looking for something similar for hours!!!

    One problem I cant see all the code and modifications (blank... =\)
    can you send the example code to -misterish86@gmail.com ?

    TNX again, def going to my fav bar... =)
    keep up the good work,
    cheers.

    ReplyDelete
  24. Sure , I will update the blog with complete running code....

    ReplyDelete
  25. Hi Mukesh Yadav,

    Can u please update this post. My email id is shankarraopilli@gmail.com. if u don't mind can i get the source code.

    Really i didn't get ur post.

    ReplyDelete
  26. Hello Shankar,
    Sure, soon I will upload the complete code.

    ReplyDelete
  27. Mukesh it would have been appreciable if you could provide some code for scaling as it has been showing vm out of memory issue to many using the above code.

    ReplyDelete
  28. Hello Friends, I just uploaded the complete source code on my git repository, you can find it here:
    https://github.com/mukesh4u/

    ReplyDelete
  29. Hi,

    I want to be able to zoom into the image and have the circle also increase in size, basically pinch the image, have it zoom in as well as circle.

    Any idea how I could do this?

    Thanks
    AA

    ReplyDelete
  30. Hi Mukesh
    I added the above code in my application. But its not working. Can you please figure out where I am doing wrong.
    I am calling a function crop2 on clicking of a button.
    code is here --
    http://paste.ubuntu.com/6111641/

    ReplyDelete
  31. Hello Mukesh,

    I am using your source code from git.
    after it execute line

    startActivityForResult(cropIntent, PIC_CROP);

    in performcrop() function, its not entering onActivityResult() fuction.

    I can see that it is failing at line

    if (resultCode == RESULT_OK)
    [ while its not failing at this line when onActivityResult() is being called by startActivityForResult(captureIntent, CAMERA_CAPTURE); line ]

    Any idea why its happening.

    I am using Eclipse and virtual device manager.

    ReplyDelete
  32. Hello Mukesh, it is a very nice tutorial....
    can you help me out to make this kind of shape

    http://fiddle.jshell.net/x4pVy/404/show/

    ReplyDelete
  33. Hey Mukesh, I have used your code and works perfectly fine. But you have fixed the height and width of target bitmap. Due to this my image is displaying small on large screen size.
    Please Help...!!!!

    ReplyDelete
  34. Hey thanks for posting this.
    but precision of image is not clear .and when i am using this code

    Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
    targetHeight,Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(targetBitmap);
    final Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setFilterBitmap(true);
    paint.setDither(true);

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);

    Bitmap sourceBitmap = scaleBitmapImage;
    final Rect rect = new Rect(0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight());
    //final RectF rectF = new RectF(rect);
    canvas.drawCircle(((float) targetWidth - 1) / 2,
    ((float) targetHeight - 1) / 2,
    (Math.min(((float) targetWidth),
    ((float) targetHeight)) / 2), paint);
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(sourceBitmap,
    rect,
    rect, paint);
    precision is clear but it is not crop center can you help me

    ReplyDelete
  35. hey mukesh can you help me ??
    i have set the image in circle and now i want to set border around the image??
    So help me by providing solution

    ReplyDelete
  36. Thanks, Great tutorial!

    ReplyDelete
  37. hellor sir ..i m new here.
    i want to perform a task for my app in which user can select image from gallery or camera and crop it and display ....can u help me in doing this task please

    ReplyDelete
  38. Hi Mukesh Yadav,

    Can u please update this post. My email id is okky.agung.w@gmail.com. if u don't mind can i get the source code.

    Thanks

    ReplyDelete

 

Copyright @ 2013 Android Developers Blog.