Kotlin编程Android开发程序员

64. (andriod开发)选择本地图片

2018-01-18  本文已影响59人  厚土火焱

选择本地图片是在打开本地文件路径的时候,通过文件类型进行一次筛选,利用手机本身的内容获取功能来实现。
一个按钮动作,根据权限判断是否需要申请。

        //选择本地图片
        btnChoiceLocalPhoto.setOnClickListener {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, arrayOf<String>(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1);
            } else {
                openAlbum();
            }
        }
    //打开相册
    fun openAlbum() {
        intent = Intent("android.intent.action.GET_CONTENT")
        intent.setType("image/*")
        startActivityForResult(intent, CHOOSE_PHOTO)//打开相册
    }

选择图片文件之后,返回后

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            CHOOSE_PHOTO -> {
                if (resultCode == Activity.RESULT_OK) {
                    //判断手机系统版本号
                    if (Build.VERSION.SDK_INT >= 19) {
                        //4.4及以上系统使用这个方法处理图片
                        handleImageOnKitKat(data)
                    } else {
                        //4.4以下系统使用这个方法处理图片
                        handeleImageBeforeKitKat(data)
                    }
                }
            }
        }
    }

辅助方法

    private fun handleImageOnKitKat(data: Intent) {
        //        Toast.makeText(this,"到了handleImageOnKitKat(Intent data)方法了", Toast.LENGTH_LONG).show();
        var imagePath: String? = null
        val uri = data.data
        if (DocumentsContract.isDocumentUri(this, uri)) {
            //如果是 document 类型的 Uri,则通过 document id 处理
            val docId = DocumentsContract.getDocumentId(uri)
            if ("com.android.providers.media.documents" == uri!!.authority) {
                val id = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[1]//解析出数字格式的 id
                val selection = MediaStore.Images.Media._ID + "=" + id
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection)
            } else if ("com.android.providers.downloads.documents" == uri.authority) {
                val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(docId)!!)
                imagePath = getImagePath(contentUri, null)
            }
        } else if ("content".equals(uri!!.scheme, ignoreCase = true)) {
            //如果是 content 类型的 uri , 则使用普通方式处理
            imagePath = getImagePath(uri, null)
        } else if ("file".equals(uri.scheme, ignoreCase = true)) {
            //如果是 file 类型的 Uri,直接获取图片路径即可
            imagePath = uri.path
        }
        displayImage(imagePath)//显示选中的图片
    }

    private fun handeleImageBeforeKitKat(data: Intent) {
        val uri = data.data
        val imagePath = getImagePath(uri, null)
        displayImage(imagePath)
    }

    private fun getImagePath(uri: Uri?, selection: String?): String? {
        var path: String? = null
        //通过 Uri 和 selection 来获取真实的图片路径
        val 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
    }

    private fun displayImage(imagePath: String?) {
        if (imagePath != null) {

            val dm = DisplayMetrics()       //获取手机分辨率
            windowManager.defaultDisplay.getMetrics(dm)

            var options = BitmapFactory.Options()   //图像参数对象,为计算图像压缩比使用
            options.inJustDecodeBounds = true

            var bitmap = BitmapFactory.decodeFile(imagePath, options)
            var num = CofoxBitmapInSampleSize(options, dm.widthPixels, dm.heightPixels)
            options.inSampleSize = num
            options.inJustDecodeBounds = false

            nowChooseImagePath = imagePath      //保存当前选中图片的原始路径
            bitmap = BitmapFactory.decodeFile(imagePath, options)//压缩图片
            imgvwUploadImageSuccess.setImageBitmap(bitmap)
        } else {
            Toast.makeText(this, "failed to get image", Toast.LENGTH_LONG).show()
        }
    }
上一篇下一篇

猜你喜欢

热点阅读