- Android Capture Image From Camera Programmatically [Updated]
- Step to capture image from camera programmatically
- 1. Defining A FileProvider
- 2. Granting Permissions To A URI, Storage & Camera
- 3. Image Capture Using Camera
- 4. Manage Result And Show Image Over The ImageView
- Android Capture Image from Camera and Gallery
- Android Tutorial
- Android Capture Image Overview
- Android Image Capture Project Structure
- Android Capture Image Code
- Android Image Capture, Save in Storage and Showing in Image View
- How to take photos from the camera and gallery on android?
- RUN-Time Permission for Camera and External Storage
- Choose Image from Camera and Gallery
- Accessing the Camera and Stored Media
Android Capture Image From Camera Programmatically [Updated]
Do you want to capture an image from the camera and set it into imageview or upload it to the server? then, this is the right post to learn.
The camera is a very common feature that lots of apps provide. Most of the required image capture feature in own application. eg. profile image, creating a post with an image, every food or social media app required camera feature in own application.
Basically, Image capturing is a very simple task, even if you are using custom. In this article, we are going to see how to capture images from the camera using FileProvider in your Android app.
Google introduces FileProvider in version 22.1.0. FileProvider class is a derived class from ContentProvider. In other words you can say, FileProvider provide facilitates to secure file sharing in android via content://Uri instead of a file:///Uri
checkout my other useful post:
So, Let’s start with how can we achieve capturing an image from the camera and getting the file path, and load an image in an ImageView.
Table of Contents
Step to capture image from camera programmatically
- Defining a FileProvider
- Granting Permissions to a URI, Storage & Camera
- Image Capture using Camera
- Manage Result and show image over the ImageView
1. Defining A FileProvider
Define a list of file paths for FileProvider in XML file and save it in res/xml folder. Since we want to save only in the public picture directory, we’ll just add the path of it to XML.
File Provider Location
In AndroidMenifest.xml you have to specify the FileProvider component by adding an element
Note — Replace com.example.captureimage with your package name
2. Granting Permissions To A URI, Storage & Camera
you need to add the permission in the manifest file as,
In the permission, the android:required=”true” is to tell Google’s play to filter all the Android devices which have a camera function.
If we use android:required=”false”, we need to check for the camera via programmatically.
Android 6, contains a permission system for certain tasks. Each application can request the required permission on runtime. So let’s open the Activity class add the below code for requesting runtime permission,
3. Image Capture Using Camera
Now let’s create a function to generate a random file name with .jpg extension in the external files directory.
We need to create an Image file
Create a new Intent with FileProvider URI
4. Manage Result And Show Image Over The ImageView
After action performing, we will manage the result on onActivityResult by using ResultCode and RequestCode. In onActivityResult, we have to manage three things.
- Get actual file path or file from result intent
- Compress a file using the FileCompressor utility
- Finally set final output over the ImageView in Android
Источник
Android Capture Image from Camera and Gallery
Android Tutorial
In this tutorial we’ll develop an application that picks an image from camera or gallery and display that in an ImageView.
Note: The below code works fine for pre-Android Nougat versions. For the latest working example check out the updated article.
Android Capture Image Overview
With the commence of Android Marshmallow, runtime permissions need to be implemented forefront.
Add the following permissions in the Android Manifest.xml file, above the application tag.
By adding android.hardware.camera, Play Store detects and prevents installing the application on devices with no camera.
Intent is the standard way to delegate actions to another application.
To start the native camera the Intent requires android.provider.MediaStore.ACTION_IMAGE_CAPTURE.
To choose an image from gallery, the Intent requires the following argument : Intent.ACTION_GET_CONTENT.
In this tutorial we’ll be invoking an image picker, that lets us select an image from camera or gallery and displays the image in a circular image view and a normal image view. Add the following dependency inside the build.gradle file.
compile ‘de.hdodenhof:circleimageview:2.1.0’
Android Image Capture Project Structure
Android Capture Image Code
The layout for the activity_main.xml stays the same barring the icon change for the FAB button to @android:drawable/ic_menu_camera .
The content_main.xml is given below:
The code for the MainActivity.java is given below
There are a lot of inferences to be drawn from the code above.
- We need to ask for the Camera runtime permissions when the user starts the activity.
- As we are starting the intent to get some result back, we need to call startActivityForResult with the relevant arguments
- Instead of using a dialog to separately call the Intents for Camera and Gallery, we’ve used a method getPickImageChooserIntent() that creates a single chooser intent for all the camera and gallery intents(note the documents intent). Intent.EXTRA_INITIAL_INTENTS is used to add the multiple application intents at one place
- For the camera intent, MediaStore.EXTRA_OUTPUT is passed as an extra to specify the image storage path. Without this you’ll be returned only a small resolution image.
- The URI path for the image returned by camera is fetched inside the method getCaptureImageOutputUri() .
- The onActivityResult essentially returns a URI to the image. Some devices do return the bitmap as data.getExtras().get(«data»); .
- When an image is clicked, the camera screen while returning restarts the activity thereby causing the URI stored from the method getCaptureImageOutputUri() to become null.
Hence it’s essential that we store and restore that URI using onSaveInstanceState() and onRestoreInstanceState() . - The bitmap is retrieved from the URI in the following line of code.
myBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), picUri); - Devices like Samsung galaxy are known to capture the image in landscape orientation. Retrieving the image and displaying as it is can cause it to be displayed in the wrong orientation. Hence we’ve called the method rotateImageIfRequired(myBitmap, picUri);
- ExifInterface is a class for reading and writing Exif tags in a JPEG file or a RAW image file.
- In the end we call the method getResizedBitmap() to scale the bitmap by width or height(whichever is larger) and set the image to the image view using setImageBitmap.
The output of the application in action is given below. Note: To capture and display an image from camera you’ll need to run the application on a smartphone for obvious reasons.
This brings an end to this tutorial. You can download the Android project for Image Capture from the link below.
Источник
Android Image Capture, Save in Storage and Showing in Image View
Nov 3, 2018 · 4 min read
Starting Android learning is very simple, This technology learning can be started very easily. But the depth of this technology is very deep, so that the learning process get harder gradually. Today I will talk about a very easy topic.
About Topic: Today we will learn to capture image with Android camera , store it in local storage and showing it on ImageView.
Let’s see , we have a button we will open the camera and capture image with this button. We have an Imageview and we will show that image in this imageview. So, firstly we need a layout file for this. This layout file can be look like this,
This first part is very easy, let’s see their is a method called captureImage() in the button onclick listener. So this method can be look like this,
When for our app we take help or do any job from another app( like camera app) than the result of that job is taken with a built in method called onActivityResult(), this method is like this,
So, When we will take picture How can we get result from this method?OK, if we look at the method, we can see this method returned with some values, they are, requestCode, resultCode and data.here, Here requestCode is the value of what we requested for, resultcode is the data that returned the value, that shows the work is done correctly, and the data is the result of the work done. So if we have an Imageview the easiest way of this code is like below
This tutorial can be finished here, but there is still a little problem for us. The problem is the bitmap/ image we are getting now that is actually a Thumbnail . In that case the size and the resolution of that image will be very low. Lets get ride from this problem , there is some steps which can helps us to get solution of this problem.
- Firstly we need a Content Provider class which we can use in camera activity. With this class we can save our photo captured with camera. This Content provider class can be look like below,
In this class “ com.xxxx.xxxx.xxx” is the package name of MY demo app. You need to use your app’s package name here . Please double check this part.
2. Now we will declare our content provider class in our manifest. And also we will add some permission related code here. The permissions are,
and the provider will be declared within the tag as like the Activities are.
In this class “ com.xxxx.xxxx.xxx” is the package name of MY demo app. You need to use your app’s package name here . Please double check this part.
Now back to the previous captureImage() method. this method will be look like this now,
Now is the time for our onActivityResult . The code in onActivityResult will be like this,
Now we can have the right image in our imageview with it’s actual size and resolution.
Here is now an important matter to remember, in android devices if the operating system is marshmallow or higher than, run time permission is needed. In that case the content provider class will help in runtime permission for storage but camera permission code need to be written before open the camera.
Here isPermissionCameraGranted() method will do work like bellow,
If the permission was not granted at the first time thane permission will be asked and the result will be like bellow,
If the user grant the permission dialog , than our captureImage() method will do it’s work.
This is all for today, will write about various topic of advance android very soon.
Источник
How to take photos from the camera and gallery on android?
With respect to an Android novice, to test things out, you would require a straightforward and clear guide. As you can discover, there are numerous articles, sites, and aides on this subject. However, a large portion of them is not working as well as haven’t tried or too complex to even think about understanding. Let me take you through a guide on the most proficient method to execute this without any problem.
you can download the full source code from Github.
First, you must have a ImageView in your layout implemented to capture the image you upload either through the camera or Gallery.
Following is my ImageView implementation for the above purpose.
Now, after doing this your activity_main.xml will look like this.
Now in the MainActivity class, you have to declare the ImageView first.
In the onCreate override method, you have to initialize the ImageView element by adding the following,
RUN-Time Permission for Camera and External Storage
as you aware that if you are working with marshmallow or above version device then you need to take first run time permission. for our app, we will require two run time permission.
- Camera Permission
- External Storage Permission
So let’s see how you will get this permission
first you need to define this two permission in your manifest file ie. AndroidManifest.xml
Now, your AndroidManifest.xml will look like this:
Okay after adding this two permission on the manifest file you need to make a function to check runtime permission on MainActivity. This function will show a popup if the user doesn’t have permission so that the user can click on the allow button to grant permission to your APP.
Now you need to Override onRequestPermissionsResult where you will handle your permission result. if permission granted then you can proceed to call chooseImage function.
Choose Image from Camera and Gallery
Now let’s see chooseImage function, which will show a dialog with three option
- Take Photo
- choose a photo from the gallery
- Exit
Now to handle the result of your startActivityForResult, you need to override onActivityResult
Once you are done with all of the steps, then you call the permission check function in the onCreate method.
So after doing all of the things your MainActivity.java will look like this
That’s it, now you can run your app and enjoy the code.
I hope you enjoy this tutorial and you have learned how to get images from the gallery or capture images from the camera on Android.
Источник
Accessing the Camera and Stored Media
This guide covers how to work with the camera and how to access media stored on the phone.
The camera implementation depends on the level of customization required:
- The easy way — launch the camera with an intent, designating a file path, and handle the onActivityResult.
- The hard way — use the Camera API to embed the camera preview within your app, adding your own custom controls.
You must configure a FileProvider as show in this section. The example below uses com.codepath.fileprovider and should match the authorities XML tag specified.
If you see a «INSTALL_FAILED_CONFLICTING_PROVIDER» error when attempting to run the app, change this to something unique, such as com.codepath.fileprovider.YOUR_APP_NAME_HERE , and also update the value in your XML tag to match.
In your AndroidManifest.xml, add the following queries block:
Easy way works in most cases, using the intent to launch the camera:
We need to define the getPhotoFileUri() function:
When the camera app finishes, the onActivityResult() method will be called:
Check out the official Photo Basics guide for more details.
In certain cases, when loading a bitmap with BitmapFactory.decodeFile(file) decoding the Bitmap in memory may actually cause a crash with a OutOfMemoryError: Failed to allocate error. Check out the Loading Bitmaps Efficiently guide and this stackoverflow post for an overview of the solutions.
Photos taken with the Camera intent are often quite large and take a very long time to load from disk. After taking a photo, you should strongly consider resizing the Bitmap to a more manageable size and then storing that smaller bitmap to disk. We can then use that resized bitmap before displaying in an ImageView .
Resizing a large bitmap and writing to disk can be done with:
Then we can write that smaller bitmap back to disk with:
Now, we can store the path to that resized image and load that from disk instead for much faster load times.
When using the Camera intent to capture a photo, the picture is always taken in the orientation the camera is built into the device. To get your image rotated correctly you’ll have to read the orientation information that is stored into the picture (EXIF meta data) and perform the following transformation using the ExifInterface Support Library:
See this guide for the source for this answer. Be aware that on certain devices even the EXIF data isn’t set properly, in which case you should checkout this workaround for a fix. You can read more here about the ExifInterface Support Library.
If you need to lookup the image type, there is the guessContentTypeFromStream() in the Java library that allows you to get back the mime type (i.e. image/jpeg ). It will read the first 16 bytes to determine the type of file. In order to use this API call, you must pass in a BufferedInputStream() which supports the mark() and reset() method calls required for the guessContentTypeFromStream() to work.
For applying filters to your captured images, check out the following libraries:
- CameraFilter — Realtime camera filters. Process frames by OpenGL shaders.
- photofilter — Apply filters to images after they are captured.
If you sure to enable access to the external storage to save to the public image, you must add this permission to your AndroidManifest.xml file:
Note: The permissions model has changed starting in Marshmallow. If your targetSdkVersion >= 23 and you are running on a Marshmallow (or later) device, you may need to enable runtime permissions. You should also read more about the runtime permissions changes.
Instead of using the capture intent to capture photos «the easy way», a custom camera can be used within your app directly leveraging the Camera2 API. This custom camera is much more complicated to implement but sample code can be found here and this CameraView from Google aims to help Android developers easily integrate Camera features. There is also a Google video overview of Camera2 which explains how Camera2 works.
There are a number of Camera2 tutorials you can review:
There are also a number of third-party libraries available to make custom cameras easier:
Leveraging Camera2 or the libraries above, apps can develop a camera that functions in anyway required including custom overlays for depositing checks, taking pictures with a particular form factor, or scanning custom barcodes.
Similar to the camera, the media picker implementation depends on the level of customization required:
- The easy way — launch the Gallery with an intent, and get the media URI in onActivityResult.
- The hard way — fetch thumbnail and full-size URIs from the MediaStore ContentProvider.
Make sure to enable access to the external storage first before using the camera (Note: The permissions model has changed starting in Marshmallow. If your targetSdkVersion >= 23 and you are running on a Marshmallow (or later) device, you may need to enable runtime permissions. You should also read more about the runtime permissions changes):
Easy way is to use an intent to launch the gallery:
Check out this Stack Overflow post for an alternate approach using mimetypes to restrict content user can select.
First, from the above example, we can add the Intent.EXTRA_ALLOW_MULTIPLE flag to the intent:
and then inside of onActivityResult , we can access all the photos selected with:
Note: that you may need to load the selected bitmaps efficiently or resize them if they are large images to avoid encountering OutOfMemoryError exceptions.
Alternatively, we can use a custom gallery selector that is implemented inside of our application to take full control over the gallery picking user experience. Check out this custom gallery source code gist or older libraries wrapping this up for reference. You can also take a look at older tutorials on custom galleries.
For allowing users to pick files from their system or online services, check out these helpful filepicker libraries:
These allow users to pick files beyond just images and are easy to drop into any app.
Источник