Pick image from gallery or camera in android kotlin example is today’s tutorial.
Pick image from gallery or camera in android kotlin tutorial guides you how to select/get the image from a gallery in android programmatically.
We will choose/take a photo from gallery or camera in the Android Studio by opening via Intent.
First, check the output of pick image from gallery or camera in android example and then we will develop it.
Creating Pick Image From Gallery Or Camera In Android Studio Tutorial step by step
Step 1: Create a new project in Android Studio.
Step 2: Updating AndroidManifest.xml file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.CAMERA" />
Note: If you are targeting SDK version above 22 (Above Lollipop) then you need to ask a user for granting runtime permissions. Check marshmallow runtime permission for more information.
Final code for AndroidManifest.xml file
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.parsaniahardik.kotlinselectimagegallery"> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.CAMERA" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Step 3: Updating activity_main.xml file
Copy and paste below source code in activity_main.xml file
<?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:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.parsaniahardik.kotlinselectimagegallery.MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btn" android:layout_gravity="center_horizontal" android:layout_marginTop="40dp" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Select or Capture Image" /> <ImageView android:layout_width="300dp" android:layout_height="300dp" android:layout_gravity="center" android:layout_marginTop="20dp" android:scaleType="fitXY" android:src="@mipmap/ic_launcher" android:id="@+id/iv"/> </LinearLayout>
Step 4: Preparing MainActivity.java class
Add following source code in MainActivity.java class
import android.app.AlertDialog import android.content.Intent import android.graphics.Bitmap import android.media.MediaScannerConnection import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.os.Environment import android.provider.MediaStore import android.util.Log import android.view.View import android.widget.Button import android.widget.ImageView import android.widget.Toast import java.io.ByteArrayOutputStream import java.io.File import java.io.FileOutputStream import java.io.IOException import java.util.* class MainActivity : AppCompatActivity() { private var btn: Button? = null private var imageview: ImageView? = null private val GALLERY = 1 private val CAMERA = 2 override fun onCreate(savedInstanceState:Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btn = findViewById<View>(R.id.btn) as Button imageview = findViewById<View>(R.id.iv) as ImageView btn!!.setOnClickListener { showPictureDialog() } } private fun showPictureDialog() { val pictureDialog = AlertDialog.Builder(this) pictureDialog.setTitle("Select Action") val pictureDialogItems = arrayOf("Select photo from gallery", "Capture photo from camera") pictureDialog.setItems(pictureDialogItems ) { dialog, which -> when (which) { 0 -> choosePhotoFromGallary() 1 -> takePhotoFromCamera() } } pictureDialog.show() } fun choosePhotoFromGallary() { val galleryIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) startActivityForResult(galleryIntent, GALLERY) } private fun takePhotoFromCamera() { val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) startActivityForResult(intent, CAMERA) } public override fun onActivityResult(requestCode:Int, resultCode:Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) /* if (resultCode == this.RESULT_CANCELED) { return }*/ if (requestCode == GALLERY) { if (data != null) { val contentURI = data!!.data try { val bitmap = MediaStore.Images.Media.getBitmap(this.contentResolver, contentURI) val path = saveImage(bitmap) Toast.makeText(this@MainActivity, "Image Saved!", Toast.LENGTH_SHORT).show() imageview!!.setImageBitmap(bitmap) } catch (e: IOException) { e.printStackTrace() Toast.makeText(this@MainActivity, "Failed!", Toast.LENGTH_SHORT).show() } } } else if (requestCode == CAMERA) { val thumbnail = data!!.extras!!.get("data") as Bitmap imageview!!.setImageBitmap(thumbnail) saveImage(thumbnail) Toast.makeText(this@MainActivity, "Image Saved!", Toast.LENGTH_SHORT).show() } } fun saveImage(myBitmap: Bitmap):String { val bytes = ByteArrayOutputStream() myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes) val wallpaperDirectory = File( (Environment.getExternalStorageDirectory()).toString() + IMAGE_DIRECTORY) // have the object build the directory structure, if needed. Log.d("fee",wallpaperDirectory.toString()) if (!wallpaperDirectory.exists()) { wallpaperDirectory.mkdirs() } try { Log.d("heel",wallpaperDirectory.toString()) val f = File(wallpaperDirectory, ((Calendar.getInstance() .getTimeInMillis()).toString() + ".jpg")) f.createNewFile() val fo = FileOutputStream(f) fo.write(bytes.toByteArray()) MediaScannerConnection.scanFile(this, arrayOf(f.getPath()), arrayOf("image/jpeg"), null) fo.close() Log.d("TAG", "File Saved::--->" + f.getAbsolutePath()) return f.getAbsolutePath() } catch (e1: IOException) { e1.printStackTrace() } return "" } companion object { private val IMAGE_DIRECTORY = "/demonuts" } }
Step 5: Description of MainActivity.java
When the user clicks the button, dialog with select options appears.
Following is button click method.
btn!!.setOnClickListener { showPictureDialog() }
The dialog contains options whether to select an image from gallery or to capture from camera.
Below is the code for showPictureDialog() method.
private fun showPictureDialog() { val pictureDialog = AlertDialog.Builder(this) pictureDialog.setTitle("Select Action") val pictureDialogItems = arrayOf("Select photo from gallery", "Capture photo from camera") pictureDialog.setItems(pictureDialogItems ) { dialog, which -> when (which) { 0 -> choosePhotoFromGallary() 1 -> takePhotoFromCamera() } } pictureDialog.show() }
If a user selects gallery, then following method is executed.
fun choosePhotoFromGallary() { val galleryIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) startActivityForResult(galleryIntent, GALLERY) }
And if user choose camera, then below method is run.
private fun takePhotoFromCamera() { val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) startActivityForResult(intent, CAMERA) }
After selecting an image from gallery or capturing photo from camera, an onActivityResult() method is executed.
Code for onActivityResult(), is as below.
public override fun onActivityResult(requestCode:Int, resultCode:Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) /* if (resultCode == this.RESULT_CANCELED) { return }*/ if (requestCode == GALLERY) { if (data != null) { val contentURI = data!!.data try { val bitmap = MediaStore.Images.Media.getBitmap(this.contentResolver, contentURI) val path = saveImage(bitmap) Toast.makeText(this@MainActivity, "Image Saved!", Toast.LENGTH_SHORT).show() imageview!!.setImageBitmap(bitmap) } catch (e: IOException) { e.printStackTrace() Toast.makeText(this@MainActivity, "Failed!", Toast.LENGTH_SHORT).show() } } } else if (requestCode == CAMERA) { val thumbnail = data!!.extras!!.get("data") as Bitmap imageview!!.setImageBitmap(thumbnail) saveImage(thumbnail) Toast.makeText(this@MainActivity, "Image Saved!", Toast.LENGTH_SHORT).show() } }
If an image comes from an gallery, then compiler goes at below code.
if (requestCode == GALLERY) { if (data != null) { val contentURI = data!!.data try { val bitmap = MediaStore.Images.Media.getBitmap(this.contentResolver, contentURI) val path = saveImage(bitmap) Toast.makeText(this@MainActivity, "Image Saved!", Toast.LENGTH_SHORT).show() imageview!!.setImageBitmap(bitmap) } catch (e: IOException) { e.printStackTrace() Toast.makeText(this@MainActivity, "Failed!", Toast.LENGTH_SHORT).show() } } }
If a photo is from a camera, then compiler goes to following.
else if (requestCode == CAMERA) { val thumbnail = data!!.extras!!.get("data") as Bitmap imageview!!.setImageBitmap(thumbnail) saveImage(thumbnail) Toast.makeText(this@MainActivity, "Image Saved!", Toast.LENGTH_SHORT).show() }
Below is the method to save the image or photo.
fun saveImage(myBitmap: Bitmap):String { val bytes = ByteArrayOutputStream() myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes) val wallpaperDirectory = File( (Environment.getExternalStorageDirectory()).toString() + IMAGE_DIRECTORY) // have the object build the directory structure, if needed. Log.d("fee",wallpaperDirectory.toString()) if (!wallpaperDirectory.exists()) { wallpaperDirectory.mkdirs() } try { Log.d("heel",wallpaperDirectory.toString()) val f = File(wallpaperDirectory, ((Calendar.getInstance() .getTimeInMillis()).toString() + ".jpg")) f.createNewFile() val fo = FileOutputStream(f) fo.write(bytes.toByteArray()) MediaScannerConnection.scanFile(this, arrayOf(f.getPath()), arrayOf("image/jpeg"), null) fo.close() Log.d("TAG", "File Saved::--->" + f.getAbsolutePath()) return f.getAbsolutePath() } catch (e1: IOException) { e1.printStackTrace() } return "" }
In above code, IMAGE_DIRECTORY is the folder name in which all the images will be saved.
JAVA Version
Java version of this tutorial : Get Image From Gallery Android
Other information regarding this tutorial
So that’s all for pick image from gallery or camera in android kotlin example. If you have queries, then ask them in the comment section. Thank you š
Download Source Code
[sociallocker]Download KotlinSelectImageGallery[/sociallocker]