Android Kotlin打开相机拍照和选择图片

MainActivity.kt

package com.example.fredric.takephoto

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.support.annotation.RequiresApi
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v4.content.FileProvider
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import java.io.File
import java.io.IOException
import android.content.ContentUris



class MainActivity : AppCompatActivity() {

    val TAKE_PHOTO: Int = 1
    val CHOOSE_PHOTO: Int = 2

    var picture: ImageView? = null
    var imageUri: Uri? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var takePhoto = findViewById<Button>(R.id.take_photo)
        var chooseFromAlbum = findViewById<Button>(R.id.choose_from_album)

        picture = findViewById<ImageView>(R.id.picture)

        takePhoto.setOnClickListener{
            var outputImage = File(externalCacheDir,"output_image.jpg")

            try{
                if(outputImage.exists()) {
                    outputImage.delete()
                }
            }catch (ex: IOException) {
                ex.printStackTrace()
            }

            if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                imageUri = Uri.fromFile(outputImage)
            }else {
                imageUri = FileProvider.getUriForFile(MainActivity@this,"com.example.fredric.takephoto.fileprovider",outputImage)
            }

            val intent = Intent("android.media.action.IMAGE_CAPTURE")
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
            startActivityForResult(intent, TAKE_PHOTO)
        }


        chooseFromAlbum.setOnClickListener{
            if(ContextCompat.checkSelfPermission(MainActivity@this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity@this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),1)
            }else {
                openAlbum()
            }
        }
    }


    fun openAlbum() {
        val intent = Intent("android.intent.action.GET_CONTENT")
        intent.setType("image/*")
        startActivityForResult(intent, CHOOSE_PHOTO)
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        when(requestCode) {
            1 -> {
                if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum()
                }else {
                    Toast.makeText(MainActivity@this,"You denied this permission!!",Toast.LENGTH_SHORT).show()
                }
            }

            else -> {

            }
        }
    }


    @RequiresApi(Build.VERSION_CODES.KITKAT)
    fun handleImageOnKitkat(data:Intent?) {
        var imagePath:String? = null
        var uri = data?.data
        Log.d("TAG","handleImageOnKitkat: Uri is: "+uri)
        if(DocumentsContract.isDocumentUri(this,uri)) {
            var docId = DocumentsContract.getDocumentId(uri)
            if("com.android.providers.media.documents".equals(uri?.authority)) {
                val id = docId.split(":")[1]
                var selection = MediaStore.Images.Media._ID + "=" + id
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection)
            }else if ("com.android.providers.downloads.documents".equals(uri?.authority)) {
                val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), docId.toLong())
                imagePath = getImagePath(contentUri,null)
            }
        }else if("content".equals(uri?.scheme,true)){
            imagePath = getImagePath(uri, null)
        }else if("file".equals(uri?.scheme,true)) {
            imagePath = uri?.getPath()
        }

        displayImage(imagePath)
    }

    fun handleImageBeforeKitkat(data:Intent?) {
        val uri = data?.data
        var imagePath:String?  = getImagePath(uri,null)
        displayImage(imagePath)
    }

    fun  getImagePath(uri: Uri?, selection: String?): String? {
        var path: String? = null
        var cursor = contentResolver.query(uri,null,selection,null,null)
        if(cursor!=null) {
            if(cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))
            }
            cursor.close()
        }
        return path
    }


    fun displayImage(imagePath:String?) {
        if(imagePath!=null) {
            val bitmap = BitmapFactory.decodeFile(imagePath)
            picture?.setImageBitmap(bitmap)
        }else {
            Toast.makeText(this,"Failed to get image!!",Toast.LENGTH_SHORT).show()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when(requestCode) {
            TAKE_PHOTO -> {
                if(resultCode == Activity.RESULT_OK) {
                    try{
                        val bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(imageUri))
                        picture?.setImageBitmap(bitmap)
                    }catch (ex: Exception) {
                        ex.printStackTrace()
                    }
                }
            }

            CHOOSE_PHOTO -> {
                if(resultCode == Activity.RESULT_OK) {
                    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        handleImageOnKitkat(data)
                    }else {
                        handleImageBeforeKitkat(data)
                    }
                }
            }

            else -> {

            }
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/take_photo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Take Photo" />

    <Button
        android:id="@+id/choose_from_album"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Choose From Album" />

    <ImageView
        android:id="@+id/picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
       />




</LinearLayout>

res/xml/file_paths.xml

<?xml version="1.0" encoding="utf-8" ?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="" />
</paths>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.fredric.takephoto">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:testOnly="false"
        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>
        
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.fredric.takephoto.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true"
            >
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"/>
        </provider>
    </application>

</manifest>

运行效果如图,


Screenshot_20180722-081309-093.jpg
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容