Image selection made easier @AndroidMonk
Selecting image or capturing image is a very common task while developing android apps. This feature is mainly used while creating user profiles or chat functionality in apps.
As a developer and an android tutor I have always felt a need to have a common easy way to select image from gallery or from camera in ImageView while building Android App. So #AndroidMonk and #WiseL brings you this simple tutorial/blog to create a single file for using such feature in your apps.
Requirements: Android Studio
Prerequisite Knowledge: Basic Knowledge on Android Application Development
Creating New Project
- Create new project with name “ImageSelection”.
Click Next in above screen
2. Select the Minimum SDK for the project. In this case it is API 16
Click Next in above screen
3. Select Empty Activity
Click Next in above screen
4. Click Finish in below screen
5. We will add one more empty activity. Right click on ‘app’ in your project panel -> New -> Activity -> Empty Activity. Change name in the screen to “SelectImageActivity”. Click Finish.
User Interface Designing (Customize as per your needs)
First we will create the UI for activity_main.xml and then we will move forward to activity_select_image.xml
NOTE: In this blog we will not be focusing on User Interface.
Add ImageView in activity_main.xml (We will use this to display our selected image)
<ImageView
android:id="@+id/ivLogoWiseL"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_margin="8dp"
/>
Add Button in activity_main.xml (We will use this to call SelectImageAcitivity)
<Button
android:id="@+id/bSelectImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/ivLogoWiseL"
android:layout_centerHorizontal="true"
android:padding="8dp"
android:text="SELECT IMAGE"
android:textColor="#FFFFFF"
android:background="@color/colorPrimaryDark"
/>
Complete Code of activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.wiselteach.blog.imageselection.MainActivity">
<ImageView
android:id="@+id/ivLogoWiseL"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_margin="8dp"
/>
<Button
android:id="@+id/bSelectImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/ivLogoWiseL"
android:layout_centerHorizontal="true"
android:padding="8dp"
android:text="SELECT IMAGE"
android:textColor="#FFFFFF"
android:background="@color/colorPrimaryDark"
/>
</RelativeLayout>
Add two buttons in activity_select_image.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_select_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.wiselteach.blog.imageselection.SelectImageActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<!--BUTTON TO CAPTURE IMAGE FROM CAMERA-->
<Button
android:id="@+id/bTakePhoto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="TAKE PHOTO"
android:textColor="#FFFFFF"
android:background="@color/colorPrimaryDark"
/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<!--BUTTON TO PICK IMAGE FROM GALLERY-->
<Button
android:id="@+id/bFromGallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="FROM GALLERY"
android:textColor="#FFFFFF"
android:background="@color/colorPrimaryDark"
/>
</RelativeLayout>
</LinearLayout>
Adding Permissions
As we are using camera to capture image we will need to add permission in android manifest file to access the camera and storage.
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Add this line above application tag inside AndroidManifest.xml file
Working with MainActivity. java file
This MainActivity code will connect the button with SelectImageActivity and will display the image in imageview.
package com.wiselteach.blog.imageselection;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
// Flag to indicate which task is to be performed.
private static final int REQUEST_SELECT_IMAGE = 0;
//Creating view variables
private Button bSelectImage;
private ImageView ivLogoWiseL;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Connecting the view variables with xml views
bSelectImage = (Button) findViewById(R.id.bSelectImage);
ivLogoWiseL = (ImageView) findViewById(R.id.ivLogoWiseL);
//Setting click listener on button
bSelectImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, SelectImageActivity.class);
startActivityForResult(intent, REQUEST_SELECT_IMAGE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Checking the requestCode and resultCode to perform a specific task
if (requestCode == REQUEST_SELECT_IMAGE && resultCode == RESULT_OK){
// If image is selected successfully, set the image URI.
Uri imageUri = data.getData();
if (imageUri != null) {
// Show the image on screen.
ivLogoWiseL.setImageURI(imageUri);
}
}
}
}
Working with SelectImageActivity.java files
This activity contains two button regarding the selection of photo and will return the image in Uri format to MainActivity on completion.
package com.wiselteach.blog.imageselection;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
public class SelectImageActivity extends AppCompatActivity {
// Flag to indicate the request of the next task to be performed
private static final int REQUEST_TAKE_PHOTO = 0;
private static final int REQUEST_SELECT_IMAGE = 1;
// The URI of photo taken with camera
private Uri uriPhoto;
Button bTakePhoto;
Button bFromGallery;
// When the activity is created, set all the member variables to initial state.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_image);
bTakePhoto = (Button) findViewById(R.id.bTakePhoto);
bFromGallery = (Button) findViewById(R.id.bFromGallery);
bTakePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
takePhoto();
}
});
bFromGallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
selectImageInGallery();
}
});
}
// Deal with the result of selection of the photos and faces.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode)
{
case REQUEST_TAKE_PHOTO:
case REQUEST_SELECT_IMAGE:
if (resultCode == RESULT_OK) {
Uri imageUri;
if (data == null || data.getData() == null) {
imageUri = uriPhoto;
} else {
imageUri = data.getData();
}
Intent intent = new Intent();
intent.setData(imageUri);
setResult(RESULT_OK, intent);
finish();
}
break;
default:
break;
}
}
public void takePhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(intent.resolveActivity(getPackageManager()) != null) {
// Save the photo taken to a temporary file.
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
try {
File file = File.createTempFile("IMG_", ".jpg", storageDir);
uriPhoto = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriPhoto);
startActivityForResult(intent, REQUEST_TAKE_PHOTO);
} catch (IOException e) {
}
}
}
public void selectImageInGallery() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_SELECT_IMAGE);
}
}
}
Result/Output
On running the application and testing is you will get output something like this: (Where image will be different depending upon your selection)
Conclusion
You can directly use the SelectImageActivity file in your app to easily capture image from camera or gallery.
Feel free to contact us regarding queries in Android Development or React Native and reach out us at WiseL. More tech learning coming soon.
Reach us here
Website: http://wiselteach.com
Facebook Page: https://www.facebook.com/WiseLearningSolutions
Instagram: https://www.instagram.com/wiselteach
Google Plus: https://plus.google.com/114834973121730067007
#AndroidMonk #WiseLTeach #WiseL