ImagePicker
📸Image Picker for Android, Pick an image from Gallery or Capture a new image with Camera
Top Related Projects
Image Cropping Library for Android
Image Cropping Library for Android, optimized for Camera / Gallery.
Android library project for cropping images
Inspired by Heinrich Reimer Material Intro and developed with love from scratch
:fireworks: A well-designed local image and video selector for Android
Android's TextView that can expand/collapse like the Google Play's app description
Quick Overview
ImagePicker is an Android library that simplifies the process of selecting images from the gallery or capturing photos using the camera. It provides a clean and easy-to-use interface for image selection, cropping, and compression, making it an excellent choice for developers who need to implement image-related features in their Android applications.
Pros
- Easy integration with minimal setup required
- Supports both gallery selection and camera capture
- Includes built-in image cropping and compression features
- Customizable UI and behavior to fit various app designs
Cons
- Limited to Android platform only
- May require additional permissions handling in newer Android versions
- Some advanced features might require additional setup or dependencies
- Potential conflicts with other image-related libraries if not managed properly
Code Examples
- Basic image selection from gallery:
ImagePicker.with(this)
.galleryOnly()
.start()
- Capture image from camera with cropping:
ImagePicker.with(this)
.cameraOnly()
.crop()
.start()
- Custom image picker with compression:
ImagePicker.with(this)
.crop(16f, 9f)
.compress(1024)
.maxResultSize(1080, 1080)
.start()
Getting Started
- Add the JitPack repository to your project's
build.gradle
file:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
- Add the dependency to your app's
build.gradle
file:
dependencies {
implementation 'com.github.Dhaval2404:ImagePicker:2.1'
}
- Initialize the ImagePicker in your activity or fragment:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnPickImage.setOnClickListener {
ImagePicker.with(this)
.start()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
val uri: Uri = data?.data!!
imageView.setImageURI(uri)
}
}
}
Competitor Comparisons
Image Cropping Library for Android
Pros of uCrop
- Advanced image cropping functionality with gesture controls
- Highly customizable UI and crop options
- Supports both bitmap and Uri input types
Cons of uCrop
- Focused solely on image cropping, lacks other image picking features
- Requires more setup and configuration for basic use cases
- Larger library size due to extensive features
Code Comparison
ImagePicker:
ImagePicker.with(this)
.crop()
.compress(1024)
.maxResultSize(1080, 1080)
.start()
uCrop:
UCrop.of(sourceUri, destinationUri)
.withAspectRatio(16f, 9f)
.withMaxResultSize(maxWidth, maxHeight)
.start(this)
Summary
ImagePicker is a more comprehensive solution for image selection and basic editing, offering a simpler API for common use cases. It includes features like camera capture, gallery selection, and basic cropping.
uCrop, on the other hand, specializes in advanced image cropping with extensive customization options. It's ideal for applications requiring precise control over the cropping process but may be overkill for simpler image selection needs.
Choose ImagePicker for a quick, all-in-one solution, or uCrop for advanced cropping functionality in your Android app.
Image Cropping Library for Android, optimized for Camera / Gallery.
Pros of Android-Image-Cropper
- Specialized in image cropping with advanced features like aspect ratio, rotation, and shape customization
- Provides a standalone activity for cropping, making it easy to integrate into existing projects
- Offers more control over the cropping process, including gesture support and overlay customization
Cons of Android-Image-Cropper
- Limited to image cropping functionality, lacking built-in image picking capabilities
- Requires more setup and configuration compared to the all-in-one solution provided by ImagePicker
- May have a steeper learning curve for developers who need a simple image selection and cropping solution
Code Comparison
Android-Image-Cropper:
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this)
ImagePicker:
ImagePicker.with(this)
.crop()
.compress(1024)
.maxResultSize(1080, 1080)
.start()
Both libraries offer concise and easy-to-use APIs, but ImagePicker provides a more streamlined approach with built-in image picking and additional features like compression in a single chain of method calls. Android-Image-Cropper focuses solely on the cropping aspect, requiring separate implementation for image selection.
Android library project for cropping images
Pros of android-crop
- Lightweight and focused specifically on image cropping functionality
- Simpler integration for projects that only need cropping without additional image picking features
- More customizable cropping options and aspect ratios
Cons of android-crop
- Limited to cropping functionality only, lacking comprehensive image selection features
- Less actively maintained, with fewer recent updates and contributions
- Smaller community and fewer resources available for support
Code Comparison
ImagePicker:
ImagePicker.with(this)
.crop()
.compress(1024)
.maxResultSize(1080, 1080)
.start()
android-crop:
Crop.of(sourceUri, destinationUri).asSquare().start(activity);
ImagePicker offers a more fluent API with chained methods for various options, while android-crop provides a simpler, more concise approach focused solely on cropping. ImagePicker's code snippet demonstrates additional features like compression and size constraints, which are not available in android-crop's basic implementation.
Both libraries serve different purposes, with ImagePicker offering a more comprehensive solution for image selection and manipulation, while android-crop focuses exclusively on the cropping aspect. The choice between the two depends on the specific requirements of your project and the range of functionality needed.
Inspired by Heinrich Reimer Material Intro and developed with love from scratch
Pros of material-intro-screen
- Specifically designed for creating app introduction screens
- Offers customizable animations and transitions
- Provides built-in progress indicator for multi-step intros
Cons of material-intro-screen
- Limited to intro screen functionality, less versatile than ImagePicker
- Less actively maintained (last update was 4 years ago)
- Fewer customization options for image handling
Code Comparison
material-intro-screen:
class IntroActivity : MaterialIntroActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addSlide(SimpleSlide.Builder()
.title("Title")
.description("Description")
.image(R.drawable.image)
.build())
}
}
ImagePicker:
ImagePicker.with(this)
.crop()
.compress(1024)
.maxResultSize(1080, 1080)
.start()
material-intro-screen focuses on creating intro slides, while ImagePicker provides a more comprehensive solution for image selection and manipulation. ImagePicker offers more flexibility and is actively maintained, making it a better choice for general image-related tasks. However, if you specifically need an intro screen solution, material-intro-screen might be more suitable despite its limitations.
:fireworks: A well-designed local image and video selector for Android
Pros of Matisse
- More customizable UI and theming options
- Built-in support for multiple image selection
- Includes image cropping functionality
Cons of Matisse
- Larger library size and potentially higher resource usage
- Less frequent updates and maintenance compared to ImagePicker
- Steeper learning curve for implementation
Code Comparison
Matisse:
Matisse.from(MainActivity.this)
.choose(MimeType.ofImage())
.countable(true)
.maxSelectable(9)
.gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
.restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
.thumbnailScale(0.85f)
.imageEngine(new GlideEngine())
.forResult(REQUEST_CODE_CHOOSE);
ImagePicker:
ImagePicker.with(this)
.crop()
.compress(1024)
.maxResultSize(1080, 1080)
.start()
The code comparison shows that Matisse offers more configuration options in a single chain, while ImagePicker provides a more concise API for basic image picking and processing. Matisse's code demonstrates its support for multiple image selection and customization, whereas ImagePicker focuses on simplicity and ease of use for single image operations.
Android's TextView that can expand/collapse like the Google Play's app description
Pros of ExpandableTextView
- Specifically designed for text expansion, providing a smooth and native-like experience for displaying long text content
- Offers customizable animation for expanding and collapsing text
- Lightweight and focused on a single functionality, potentially easier to integrate for text-specific use cases
Cons of ExpandableTextView
- Limited to text manipulation, lacking image handling capabilities
- Less actively maintained, with fewer recent updates compared to ImagePicker
- Narrower scope of functionality, which may require additional libraries for more comprehensive UI components
Code Comparison
ExpandableTextView implementation:
<com.ms.square.android.expandabletextview.ExpandableTextView
android:id="@+id/expand_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
expandableTextView:maxCollapsedLines="4"
expandableTextView:animDuration="200">
</com.ms.square.android.expandabletextview.ExpandableTextView>
ImagePicker implementation:
ImagePicker.with(this)
.crop()
.compress(1024)
.maxResultSize(1080, 1080)
.start()
While ExpandableTextView focuses on text expansion functionality, ImagePicker provides a comprehensive solution for image selection and manipulation. The choice between these libraries depends on the specific requirements of your project, with ExpandableTextView being more suitable for text-centric applications and ImagePicker offering broader image-related features.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
ð¸Image Picker Library for Android
Easy to use and configurable library to Pick an image from the Gallery or Capture image using Camera. It also allows to Crop and Compresses the Image based on Aspect Ratio, Resolution and Image Size.
Almost 90% of the app that I have developed has an Image upload feature. Along with the image selection, Sometimes I needed a crop feature for profile image for that I've used uCrop. Most of the time I need to compress the image as the image captured from the camera is more than 5-10 MBs and sometimes we have a requirement to upload images with specific resolution/size, in that case, image compress is the way to go option. To simplify the image pick/capture option I have created ImagePicker library. I hope it will be useful to all.
ð±âðFeatures:
- Pick Gallery Image
- Pick Image from Google Drive
- Capture Camera Image
- Crop Image (Crop image based on provided aspect ratio or let user choose one)
- Compress Image (Compress image based on provided resolution and size)
- Retrieve Image Result as Uri object (Retrieve as File object feature is removed in v2.0 to support scope storage)
- Handle runtime permission for camera
- Does not require storage permission to pick gallery image or capture new image.
ð¬Preview
Profile Image Picker | Gallery Only | Camera Only |
---|---|---|
ð»Usage
-
Gradle dependency:
allprojects { repositories { maven { url "https://jitpack.io" } } }
implementation 'com.github.dhaval2404:imagepicker:2.1'
If you are yet to Migrate on AndroidX, Use support build artifact:
implementation 'com.github.dhaval2404:imagepicker-support:1.7.1'
-
The ImagePicker configuration is created using the builder pattern.
Kotlin
ImagePicker.with(this) .crop() //Crop image(Optional), Check Customization for more option .compress(1024) //Final image size will be less than 1 MB(Optional) .maxResultSize(1080, 1080) //Final image resolution will be less than 1080 x 1080(Optional) .start()
Java
ImagePicker.with(this) .crop() //Crop image(Optional), Check Customization for more option .compress(1024) //Final image size will be less than 1 MB(Optional) .maxResultSize(1080, 1080) //Final image resolution will be less than 1080 x 1080(Optional) .start()
-
Handling results
Override
onActivityResult
method and handle ImagePicker result.override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK) { //Image Uri will not be null for RESULT_OK val uri: Uri = data?.data!! // Use Uri object instead of File to avoid storage permissions imgProfile.setImageURI(fileUri) } else if (resultCode == ImagePicker.RESULT_ERROR) { Toast.makeText(this, ImagePicker.getError(data), Toast.LENGTH_SHORT).show() } else { Toast.makeText(this, "Task Cancelled", Toast.LENGTH_SHORT).show() } }
Inline method (with registerForActivityResult, Only Works with FragmentActivity and AppCompatActivity)
i. Add required dependency for registerForActivityResult API
implementation "androidx.activity:activity-ktx:1.2.3" implementation "androidx.fragment:fragment-ktx:1.3.3"
ii. Declare this method inside fragment or activity class
private val startForProfileImageResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult -> val resultCode = result.resultCode val data = result.data if (resultCode == Activity.RESULT_OK) { //Image Uri will not be null for RESULT_OK val fileUri = data?.data!! mProfileUri = fileUri imgProfile.setImageURI(fileUri) } else if (resultCode == ImagePicker.RESULT_ERROR) { Toast.makeText(this, ImagePicker.getError(data), Toast.LENGTH_SHORT).show() } else { Toast.makeText(this, "Task Cancelled", Toast.LENGTH_SHORT).show() } }
iii. Create ImagePicker instance and launch intent
ImagePicker.with(this) .compress(1024) //Final image size will be less than 1 MB(Optional) .maxResultSize(1080, 1080) //Final image resolution will be less than 1080 x 1080(Optional) .createIntent { intent -> startForProfileImageResult.launch(intent) }
ð¨Customization
-
Pick image using Gallery
ImagePicker.with(this) .galleryOnly() //User can only select image from Gallery .start() //Default Request Code is ImagePicker.REQUEST_CODE
-
Capture image using Camera
ImagePicker.with(this) .cameraOnly() //User can only capture image using Camera .start()
-
Crop image
ImagePicker.with(this) .crop() //Crop image and let user choose aspect ratio. .start()
-
Crop image with fixed Aspect Ratio
ImagePicker.with(this) .crop(16f, 9f) //Crop image with 16:9 aspect ratio .start()
-
Crop square image(e.g for profile)
ImagePicker.with(this) .cropSquare() //Crop square image, its same as crop(1f, 1f) .start()
-
Compress image size(e.g image should be maximum 1 MB)
ImagePicker.with(this) .compress(1024) //Final image size will be less than 1 MB .start()
-
Set Resize image resolution
ImagePicker.with(this) .maxResultSize(620, 620) //Final image resolution will be less than 620 x 620 .start()
-
Intercept ImageProvider, Can be used for analytics
ImagePicker.with(this) .setImageProviderInterceptor { imageProvider -> //Intercept ImageProvider Log.d("ImagePicker", "Selected ImageProvider: "+imageProvider.name) } .start()
-
Intercept Dialog dismiss event
ImagePicker.with(this) .setDismissListener { // Handle dismiss event Log.d("ImagePicker", "onDismiss"); } .start()
-
Specify Directory to store captured, cropped or compressed images. Do not use external public storage directory (i.e. Environment.getExternalStorageDirectory())
ImagePicker.with(this) /// Provide directory path to save images, Added example saveDir method. You can choose directory as per your need. // Path: /storage/sdcard0/Android/data/package/files .saveDir(getExternalFilesDir(null)!!) // Path: /storage/sdcard0/Android/data/package/files/DCIM .saveDir(getExternalFilesDir(Environment.DIRECTORY_DCIM)!!) // Path: /storage/sdcard0/Android/data/package/files/Download .saveDir(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)!!) // Path: /storage/sdcard0/Android/data/package/files/Pictures .saveDir(getExternalFilesDir(Environment.DIRECTORY_PICTURES)!!) // Path: /storage/sdcard0/Android/data/package/files/Pictures/ImagePicker .saveDir(File(getExternalFilesDir(Environment.DIRECTORY_PICTURES)!!, "ImagePicker")) // Path: /storage/sdcard0/Android/data/package/files/ImagePicker .saveDir(getExternalFilesDir("ImagePicker")!!) // Path: /storage/sdcard0/Android/data/package/cache/ImagePicker .saveDir(File(getExternalCacheDir(), "ImagePicker")) // Path: /data/data/package/cache/ImagePicker .saveDir(File(getCacheDir(), "ImagePicker")) // Path: /data/data/package/files/ImagePicker .saveDir(File(getFilesDir(), "ImagePicker")) // Below saveDir path will not work, So do not use it // Path: /storage/sdcard0/DCIM // .saveDir(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)) // Path: /storage/sdcard0/Pictures // .saveDir(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)) // Path: /storage/sdcard0/ImagePicker // .saveDir(File(Environment.getExternalStorageDirectory(), "ImagePicker")) .start()
-
Limit MIME types while choosing a gallery image
ImagePicker.with(this) .galleryMimeTypes( //Exclude gif images mimeTypes = arrayOf( "image/png", "image/jpg", "image/jpeg" ) ) .start()
-
You can also specify the request code with ImagePicker
ImagePicker.with(this) .maxResultSize(620, 620) .start(101) //Here 101 is request code, you may use this in onActivityResult
-
Add Following parameters in your colors.xml file, If you want to customize uCrop Activity.
<resources> <!-- Here you can add color of your choice --> <color name="ucrop_color_toolbar">@color/teal_500</color> <color name="ucrop_color_statusbar">@color/teal_700</color> <color name="ucrop_color_widget_active">@color/teal_500</color> </resources>
ð¥Compatibility
- Library - Android Kitkat 4.4+ (API 19)
- Sample - Android Kitkat 4.4+ (API 19)
âï¸Changelog
Version: 2.1
- Added uzbekistan translation (Special Thanks to Khudoyshukur Juraev)
- Removed requestLegacyExternalStorage flag
- Removed unused string resources
Version: 2.0
- Added arabic translation #157 (Special Thanks to zhangzhu95)
- Added norwegian translation #163 (Special Thanks to TorkelV)
- Added german translation #192 (Special Thanks to MDXDave)
- Added method to return Intent for manual launching ImagePicker #182 (Special Thanks to tobiasKaminsky)
- Added support for android 11 #199
- Fixed android scope storage issue #29
- Removed storage permissions #29
- Fixed calculateInSampleSize leads to overly degraded quality #152 (Special Thanks to FlorianDenis)
- Fixed camera app not found issue #162
- Fixed Playstore requestLegacyExternalStorage flag issue #199
Version: 1.8
- Added dialog dismiss listener (Special Thanks to kibotu)
- Added text localization (Special Thanks to yamin8000 and Jose Bravo)
- Fixed crash issue on missing camera app #69
- Fixed issue selecting images from download folder #86
- Fixed exif information lost issue #121
- Fixed crash issue on large image crop #122
- Fixed saving image in cache issue #127
Version: 1.7
- Added option to limit MIME types while choosing a gallery image (Special Thanks to Marchuck)
- Introduced ImageProviderInterceptor, Can be used for analytics (Special Thanks to Marchuck)
- Fixed .crop() opening gallery or camera twice #32
- Fixed FileProvider of the library clashes with the FileProvider of the app #51 (Special Thanks to OyaCanli)
- Added option to set Storage Directory #52
- Fixed NullPointerException in FileUriUtils.getPathFromRemoteUri() #61 (Special Thanks to himphen)
- Fixed UCropActivity Crash Android 4.4 (KiKat) #82
- Fixed PNG image saved as JPG after crop issue #94
- Fixed PNG image saved as JPG after compress issue #105
- Added Polish text translation #115 (Special Thanks to MarcelKijanka)
- Failed to find configured root exception #116
Version: 1.6
- Improved UI/UX of sample app
- Removed Bitmap Deprecated Property #33 (Special Thanks to nauhalf)
- Camera opens twice when "Don't keep activities" option is ON #41 (Special Thanks to benji101)
- Fixed uCrop Crash Issue #42
Version: 1.5
- Fixed app crash issue, due to Camera Permission in manifest #34
- Added Option for Dynamic Crop Ratio. Let User choose aspect ratio #36 (Special Thanks to Dor-Sloim)
Version: 1.4
- Optimized Uri to File Conversion (Inspired by Flutter ImagePicker)
- Removed redundant CAMERA permission #26 (Special Thanks to PerrchicK)
Version: 1.3
- Sample app made compatible with Android Kitkat 4.4+ (API 19)
- Fixed Uri to File Conversion issue #8 (Special Thanks to squeeish)
Version: 1.2
- Added Support for Inline Activity Result(Special Thanks to soareseneves)
- Fixed issue #6
Version: 1.1
- Optimized Compression Logic
- Replace white screen with transparent one.
Version: 1.0
- Initial Build
ð Libraries Used
- uCrop https://github.com/Yalantis/uCrop
- Compressor https://github.com/zetbaitsu/Compressor
Let us know!
We'll be really happy if you sent us links to your projects where you use our component. Just send an email to dhavalpatel244@gmail.com And do let us know if you have any questions or suggestion regarding the library.
License
Copyright 2019-2021, Dhaval Patel
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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.
Top Related Projects
Image Cropping Library for Android
Image Cropping Library for Android, optimized for Camera / Gallery.
Android library project for cropping images
Inspired by Heinrich Reimer Material Intro and developed with love from scratch
:fireworks: A well-designed local image and video selector for Android
Android's TextView that can expand/collapse like the Google Play's app description
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot