[关闭]
@cxm-2016 2016-12-15T09:36:24.000000Z 字数 1225 阅读 4788

Android:如何打开系统相册

Android

版本:1
作者:陈小默
声明:允许规范转载


1,打开相册

  1. /**
  2. * 打开相机
  3. */
  4. private val CAMERA = 1
  5. /**
  6. * 打开相册
  7. */
  8. private val ALBUM = 2
  9. /**
  10. * 上传头像
  11. */
  12. private val UPLOAD = 3
  1. val intent = Intent(Intent.ACTION_PICK, null)
  2. intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
  3. startActivityForResult(intent, ALBUM)

2,打开相机

  1. val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
  2. intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(temp)) //保存拍照后的相片到temp文件
  3. startActivityForResult(intent, CAMERA)

3,获取结果

  1. override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
  2. when (requestCode) {
  3. CAMERA -> {
  4. if (resultCode == Activity.RESULT_OK) crop(Uri.fromFile(temp))
  5. }
  6. ALBUM -> {
  7. if (resultCode == Activity.RESULT_OK) crop(data!!.data)
  8. }
  9. UPLOAD -> {
  10. if (data != null && data.extras != null) {
  11. val extras = data.extras
  12. val head: Bitmap = extras.getParcelable("data")
  13. ...
  14. }
  15. }
  16. else -> {
  17. }
  18. }
  19. }

4,打开裁剪

  1. /**
  2. * 打开系统裁剪页面
  3. */
  4. private fun crop(uri: Uri) {
  5. val intent = Intent("com.android.camera.action.CROP")
  6. with(intent) {
  7. setDataAndType(uri, "image/*")
  8. putExtra("crop", "true")
  9. putExtra("aspectX", 1) // aspectX aspectY 是宽高的比例
  10. putExtra("aspectY", 1)
  11. intent.putExtra("outputX", 150) // outputX outputY 是裁剪图片宽高
  12. intent.putExtra("outputY", 150)
  13. intent.putExtra("return-data", true)
  14. }
  15. view.startActivityForResult(intent, UPLOAD)
  16. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注