Crop image circle android
Wanna help the project? Amazing!
Android Image Cropper
Powerful (Zoom, Rotation, Multi-Source); Customizable (Shape, Limits, Style); Optimized (Async, Sampling, Matrix); Simple image cropping library for Android.
Add to your project
Step 1. Add the JitPack repository to your root build.gradle
Step 2. Add the dependency
Step 3. Add permissions to manifest
Only need if you run on devices under OS10 (SDK 29)
Step 4. Set source compatibility version to Java 11
The library is up to date with the latest releases, if you are not using Java 11 yet please check the release page for previous working versions.
Go to app level build.gradle file
Add this line inside android in build.gradle
This expects Gradle 7.0+
Using the Library
There is 3 ways of using the library:
- Calling crop directly (Sample code: sample/crop_image )
- Using the CropView (Sample code: sample/crop_image_view )
- Extending the activity (Sample code: sample/extend_activity ) Your choice depends on how you want your layout to look.
Obs: The library has a public pick image contract, more on wiki.
Calling crop directly
- Register for activity result with CropImageContract
- Add CropImageView into your activity
Extend to make a custom activity
If you want to extend the CropImageActivity please be aware you will need to setup your CropImageView You can check a sample code in this project com.canhub.cropper.sample.extend_activity.app.SExtendActivity
- Add CropImageActivity into your AndroidManifest.xml
- Setup your CropImageView after call super.onCreate(savedInstanceState)
Custom dialog for image source pick
When calling crop directly the library will prompt a dialog for the user choose between gallery or camera (If you keep both enable). We use the Android default AlertDialog for this. If you wanna customised it with your app theme you need to override the method showImageSourceDialog(..) when extending the activity (above)
- Built-in CropImageActivity .
- Set cropping image as Bitmap, Resource or Android URI (Gallery, Camera, Dropbox, etc.).
- Image rotation/flipping during cropping.
- Auto zoom-in/out to relevant cropping area.
- Auto rotate bitmap by image Exif data.
- Set result image min/max limits in pixels.
- Set initial crop window size/location.
- Request cropped image resize to specific size.
- Bitmap memory optimization, OOM handling (should never occur)!
- API Level 14.
- More..
- Cropping window shape: Rectangular, Oval (square/circle by fixing aspect ratio), as well as rectangular modes which only allow vertical or horizontal cropping.
- Cropping window aspect ratio: Free, 1:1, 4:3, 16:9 or Custom.
- Guidelines appearance: Off / Always On / Show on Touch.
- Cropping window Border line, border corner and guidelines thickness and color.
- Cropping background color.
For more information, see the GitHub Wiki.
Forked from ArthurHub Originally forked from edmodo/cropper.
Copyright 2016, Arthur Teplitzki, 2013, Edmodo, Inc.
Licensed under the Apache License, Version 2.0 (the «License»); you may not use this work except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or at:
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an «AS IS» BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
About
Image Cropping Library for Android, optimised for Camera / Gallery.
Источник
Crop image circle android
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.
Hope , this will helps anyone.
Enjoy Coding. 🙂
Mukesh Kumar
39 comments:
thanks for code.. image is displayed in circular shape but precision is not so clear.
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);
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
This comment has been removed by the author.
Источник
Crop image circle android
Crop image via rectangle or circle shape
In this section I’ll show how to crop image via rectangle shape using Android-Image-Cropper and image from camera.
To get picture from Camera and write access to disk I’m going to use EasyPermissions.
Add the below line in your module’s build.gradle file:
Add permissions and CropImageActivity into your AndroidManifest.xml
Following is layout for MainActivity.
Following is MainActivity.
Android 7.0 Nougat introduced some file system permission changes in order to improve security. If you’ve already updated your app to targetSdkVersion 24 (or higher) and you’re passing a file:// URI outside your package domain through an Intent , then what you’ll get is a FileUriExposedException .
So, Android may throw FileUriExposedException in Android 7.0 (API level 24) and above, this exception will come when you will expose a file:// URIs outside your package domain through Intent .
FileProvider is a special subclass of ContentProvider which allows us to securely share file through a content:// URI instead of file:// one. Why is this a better approach? Because you’re granting a temporary access to the file, which will be available for the receiver activity or service until they are active/running.
We create our own class inheriting FileProvider in order to make sure our FileProvider doesn’t conflict with FileProviders declared in imported dependencies as described here.
Add a class extending FileProvider
Next, add the GenericFileProvider in our AndroidManifest.xml:
We’re going to set android:exported to false because we don’t need it to be public, android:grantUriPermissions to true because it will grant temporary access to files and android:authorities to a domain you control, so if your domain is me.proft.superapp then you can use something like me.proft.superapp.provider . The authority of a provider should be unique and that’s the reason why we are using our application ID plus something like .provider.
Then we need to create the file_provider_path in the res/xml folder. That’s the file which defines the folders which contain the files you will be allowed to share safely. In our case we just need access to the external storage folder:
The final step is to change the line of code below in
If you’re using an Intent to make the system open your file, you may need to add the following line of code:
Instead of using Uri.fromFile(file) we create our URI with FileProvider.getUriForFile(context, string, file) which will generate a new content:// URI with the authority defined pointing to the file we passed in.
Other useful libs for image crop:
Crop image via custom shape from bitmap
Sometimes you want to crop a bitmap, but it’s not an ordinary cropping, it’s a cropping to get rounded corners, cropping to get it as a circle, cropping to get it as a star, or cropping to get it as any shape.
In this post, we will crop a heart from an Android bitmap.
At first get a bitmap to crop a shape from it.
Create an empty and mutable bitmap with the same height and width of the source.
Create a canvas with the mutable bitmap to draw into.
Create a paint with any solid color, this color is for drawing a heart which you want to crop from the bitmap.
Draw a heart path at the center of the canvas.
In our case, the heart shape which you have drawn is called the destination image, it’s the shape which you want to crop from the bitmap.
The magic will be in the next line of code, set the transfer mode which defines how source pixels are composited or merged with the destination pixels.
Draw the source image on the canvas which has the destination image and use the paint with the SRC_IN transformation mode.
Источник
Crop image circle android
A fast circular ImageView perfect for profile images. This is based on RoundedImageView from Vince Mi which itself is based on techniques recommended by Romain Guy.
It uses a BitmapShader and does not:
- create a copy of the original bitmap
- use a clipPath (which is neither hardware accelerated nor anti-aliased)
- use setXfermode to clip the bitmap (which means drawing twice to the canvas)
As this is just a custom ImageView and not a custom Drawable or a combination of both, it can be used with all kinds of drawables, i.e. a PicassoDrawable from Picasso or other non-standard drawables (needs some testing though).
- The ScaleType is always CENTER_CROP and you’ll get an exception if you try to change it. This is (currently) by design as it’s perfectly fine for profile images.
- Enabling adjustViewBounds is not supported as this requires an unsupported ScaleType
- If you use an image loading library like Picasso or Glide, you need to disable their fade animations to avoid messed up images. For Picasso use the noFade() option, for Glide use dontAnimate() . If you want to keep the fadeIn animation, you have to fetch the image into a Target and apply a custom animation yourself when receiving the Bitmap .
- Using a TransitionDrawable with CircleImageView doesn’t work properly and leads to messed up images.
How can I use a VectorDrawable with CircleImageView ?
Short answer: you shouldn’t. Using a VectorDrawable with CircleImageView is very inefficient. You should modify your vectors to be in a circular shape and use them with a regular ImageView instead.
Why doesn’t CircleImageView extend AppCompatImageView ?
Extending AppCompatImageView would require adding a runtime dependency for the support library without any real benefit.
How can I add a selector (e.g. ripple effect) bound to a circle?
There’s currently no direct support for a circle bound selector but you can follow these steps to implement it yourself.
How can I add a gap between image and border?
Adding a gap is also not supported directly but there’s a workaround.
Источник
Crop image circle android
The SimpleCropView is an image cropping library for Android.
It simplifies your code for cropping image and provides an easily customizable UI.
Supported on API Level 14 and above.
Table of Contents
Include the following dependency in your build.gradle file. Please use the latest version available.
Add permission in AndroidManifest.xml file.
Add the com.isseiaoki.simplecropview.CropImageView to your layout XML file.
NOTE: The image is scaled to fit the size of the view by maintaining the aspect ratio. WRAP_CONTENT will be ignored.
Load image from sourceUri.
Crop image and save cropped bitmap in saveUri.
SimpleCropView supports rotation by 90 degrees.
For a working implementation of this project, see sample project.
- load(sourceUri).execute(mLoadCallback);
These method load Bitmap in efficient size from sourceUri. You don’t have to care for filePath and image size. You can also use Picasso or Glide .
You can use blurred image for placeholder.
Crop and Save Image
These cropping method use full size bitmap taken from sourceUri for cropping. If sourceUri is null, the Uri set in load(Uri) is used. After cropping, it saves cropped image in saveUri .
You can use 3 compress format, PNG (default), JPEG , and WEBP .
You can also set compress quality. 0
Maximum Output Size
You can set max size for output image. The output image will be scaled within given rect.
Fixed Output Size
You can also set fixed output width/height.
The option for the aspect ratio of the image cropping frame.
FREE : Non-Fixed aspect ratio mode RATIO_X_Y , SQUARE : Fixed aspect ratio mode FIT_IMAGE : Fixed aspect ratio mode. The same aspect ratio as the original photo.
If you need other aspect ratio, use setCustomRatio(int ratioX, int ratioY);
CIRCLE : Fixed aspect ratio mode. Crop image as circle. CIRCLE_SQUARE : Fixed aspect ratio mode. Show guide circle, but save as square.( getRectBitmap() is removed.)
The minimum size of the image cropping frame in dp.(default:50)
The initial frame size of the image cropping frame. 0.01
scale | Appearance |
---|---|
0.5 | |
0.75 | |
1.0 (default) |
Save and Restore FrameRect
You can save and restore frame rect as follows. See sample project for more details.
Stroke Weight and Handle Size
Handle Touch Padding
Additional touch area for the image cropping frame handle.
Handle and Guide ShowMode
Handle ShowMode | Guide ShowMode | Appearance |
---|---|---|
SHOW_ALWAYS | SHOW_ALWAYS | |
NOT_SHOW | NOT_SHOW | |
SHOW_ALWAYS | NOT_SHOW | |
SHOW_ALWAYS | SHOW_ON_TOUCH | |
SHOW_ON_TOUCH | NOT_SHOW |
SimpleCropView supports rotate animation and frame change animation.
Toggle whether to animate. true is default.
Set animation duration in milliseconds. 100 is default.
Set interpolator of animation. DecelerateInterpolator is default. You can also use your custom interpolator.
Picasso and Glide Compatibility
com.isseiaoki.simplecropview.CropImageView is a kind of ImageView . You can use it with Picasso or Glide as follows:
Some option does not work correctly because CropImageView does not support ImageView.ScaleType.
You can use debug display.
XML sample here.
XML Attribute (custom:) | Related Method | Description |
---|---|---|
scv_img_src | setImageResource(int resId) | Set source image. |
scv_crop_mode | setCropMode(CropImageView.CropMode mode) | Set crop mode. |
scv_background_color | setBackgroundColor(int bgColor) | Set view background color. |
scv_overlay_color | setOverlayColor(int overlayColor) | Set image overlay color. |
scv_frame_color | setFrameColor(int frameColor) | Set the image cropping frame color. |
scv_handle_color | setHandleColor(int frameColor) | Set the handle color. |
scv_guide_color | setGuideColor(int frameColor) | Set the guide color. |
scv_guide_show_mode | setGuideShowMode(CropImageView.ShowMode mode) | Set guideline show mode. |
scv_handle_show_mode | setHandleShowMode(CropImageView.ShowMode mode) | Set handle show mode. |
scv_handle_size | setHandleSizeInDp(int handleDp) | Set handle radius in density-independent pixels. |
scv_touch_padding | setTouchPaddingInDp(int paddingDp) | Set the image cropping frame handle touch padding(touch area) in density-independent pixels. |
scv_min_frame_size | setMinFrameSizeInDp(int minDp) | Set the image cropping frame minimum size in density-independent pixels. |
scv_frame_stroke_weight | setFrameStrokeWeightInDp(int weightDp) | Set frame stroke weight in density-independent pixels. |
scv_guide_stroke_weight | setGuideStrokeWeightInDp(int weightDp) | Set guideline stroke weight in density-independent pixels. |
scv_crop_enabled | setCropEnabled(boolean enabled) | Set whether to show the image cropping frame. |
scv_initial_frame_scale | setInitialFrameScale(float initialScale) | Set Set initial scale of the frame.(0.01 |
1.0)
If you are using my library, please let me know your app name : )
Источник