![](https://www.gkmit.co/wp-content/uploads/2018/09/How-to-capture-image-from-camera-and-gallery-in-android.png)
How to capture image from camera and gallery in android?
How to Capture Image from Camera and Gallery in Android?
Many developers face issues when capturing an image from the camera in KitKat and Oreo, as the image quality automatically reduces. This article explains how to open the gallery on an Android phone, select images, capture an image from the camera, and save it to the gallery.
Why Image Quality Drops in KitKat and Oreo?
The default handling of images in KitKat and Oreo can lead to compression issues, resulting in lower image quality. To fix this, we need a structured approach to properly capture and store images.
Steps to Capture Image from Camera or Gallery
Step 1:
Open “AndroidManifest” and add the following code to it:
<uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" /> <uses-feature android:name="android.hardware.camera.autofocus" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"> </meta-data></provider>
Step 2:
Create file file_pathes.xml in xml folder
<?xml version="1.0" encoding="utf-8"?><paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-path name="external_files" path="." /></paths>
Step 3:
Add ImageUtils class file in your project where compress image with low or high quality.
public class ImageUtils { public ImageUtils() { } public byte[] getBytesFromBitmap(Bitmap bitmap) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 25, stream); return stream.toByteArray(); } public byte[] getBytesFromBitmapCamera(Bitmap bitmap) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); return stream.toByteArray(); } public static File getOutputMediaFile(Context context) { File mediaStorageDir; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), “GKMIT”); } else { mediaStorageDir = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), “GKMIT”); } if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d(“GKMIT”, "Oops! Failed create " + “GKMIT”+ " directory"); } } String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()); File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); return mediaFile; }}
Step 4:
Show alert dialog box on any button where you want to click and want to upload your camera or gallery image. A code is written in below.
protected static final int CAMERA_REQUEST = 100;protected static final int GALLERY_PICTURE = 101;public static final int MY_PERMISSIONS_REQUEST_CAMERA = 123;File captureMediaFile;byte[] bytesDocumentsTypePicture = null;AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);myAlertDialog.setTitle("Upload Pictures Option");myAlertDialog.setMessage("How do you want to set your picture?"); myAlertDialog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, GALLERY_PICTURE); } }); myAlertDialog.setNegativeButton("Camera", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { captureMediaFile = ImageUtils.getOutputMediaFile(getApplicationContext()); if (captureMediaFile != null) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { intent.addFlags(FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION); intent.putExtra(MediaStore.EXTRA_OUTPUT, captureMediaFile); } else { Uri photoUri = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + ".provider", captureMediaFile); intent.addFlags(FLAG_GRANT_READ_URI_PERMISSION); intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri); } if (intent.resolveActivity(getPackageManager()) != null) { startActivityForResult(intent, CAMERA_REQUEST); } else { new AlertDialogMessage(getApplicationContext()).showAToast(R.string.camera_unavailable); } } else { new AlertDialogMessage(getApplicationContext()).showAToast(R.string.file_save_error); } } }); myAlertDialog.show();}
Step 5:
onActivityResult here we can get image data
@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data);if (resultCode == RESULT_OK && requestCode == CAMERA_REQUEST) { Bitmap bitmap; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { if (data != null) { bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData()); bytesDocumentsTypePicture = new ImageUtils().getBytesFromBitmap(bitmap); } else { Toast.makeText(getApplicationContext(), " some_error_while_uploading ",Toast.LENGTH_SHORT).show(); } } else { bitmap = BitmapFactory.decodeFile(captureMediaFile.getAbsolutePath()); bytesDocumentsTypePicture = new ImageUtils().getBytesFromBitmap(bitmap); }} else if (resultCode == RESULT_OK && requestCode == GALLERY_PICTURE) { if (data != null) { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage); bytesDocumentsTypePicture = new ImageUtils().getBytesFromBitmap(bitmap); } else{ Toast.makeText(getApplicationContext(), " some_error_while_uploading ",Toast.LENGTH_SHORT).show(); }} else { Toast.makeText(getApplicationContext(), " some_error_while_uploading ",Toast.LENGTH_SHORT).show();}
bytesDocumentsTypePicture here this byte variable you can send the image on a server.
Enhancing Performance for Mobile App Development Services
Integrating proper image capture and compression techniques enhances performance in Mobile App Development Services. Efficient memory management, high-quality image storage, and optimized gallery interactions ensure a smooth user experience and app stability.
Final Thoughts
- Always request permissions before accessing the camera or gallery.
- Use FileProvider to avoid compatibility issues.
- Compress images to balance quality and performance.
- Handle errors gracefully to prevent app crashes.
By following these best practices, developers can ensure high-quality image capturing and seamless integration in Android applications.