使用ACTION_IMAGE_CAPTURE获取完整图像位图kotlin

时间:2018-05-11 17:22:10

标签: android bitmap kotlin photo

我想要做的就是让用户拍照,然后在他们填完表格后提交照片并上传到服务器。 我想我需要位图形式的图像,所以我可以转换为Base64字符串。 我尝试了多种不同的东西,但我们都没有找到它们。我要么得到目录错误,要么意图出现空错误。

class Register : AppCompatActivity(), View.OnClickListener {
    var  PlayerID = ""
    var mCurrentPhotoPath = ""
    var stuff: File? = null

    private var filePath: Uri? = null
    private val PICK_IMAGE_REQUEST = 1
    @RequiresApi(Build.VERSION_CODES.O)



    override fun onClick(v: View?) {
      if(v === buttonLoadPicture)
          showFileChooser()
        else if (v == btn_register)
          uploadFile()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
            if (resultCode != RESULT_CANCELED) {
                if (requestCode == PICK_IMAGE_REQUEST) {

                    val thumbnail = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath)
                    PhotoImageView.setImageBitmap(thumbnail)

                    filePath = getRealPathFromURI(Uri.parse(filePath.toString()))
                }
            }
        }


    //////////////
    fun  getImageUri(inContext: Context , inImage: Bitmap): Uri {
        val bytes = ByteArrayOutputStream()
        inImage.compress(Bitmap.CompressFormat.PNG, 100, bytes)
        val path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null)
        return Uri.parse(path)
    }

     fun getRealPathFromURI(uri: Uri): Uri? {
         val proj = arrayOf(MediaStore.Images.Media.DATA)
        val cursor = getContentResolver().query(uri, proj, null, null, null)

        cursor.moveToFirst()
        val idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
        return Uri.parse(cursor.getString(idx))
    }


    ////////////////
    @RequiresApi(Build.VERSION_CODES.N)
    private fun showFileChooser() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    arrayOf(Manifest.permission.CAMERA),
                    1)
        }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    1)
        }

        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        startActivityForResult(intent, 1)
    }





    val jsonobject = JSONObject()
    @RequiresApi(Build.VERSION_CODES.O)
    private fun uploadFile() {
        val progress: ProgressBar = progressBarR
        progress.visibility= View.VISIBLE

        val iStream = contentResolver.openInputStream(filePath)
        val bitmap = BitmapFactory.decodeStream(iStream)
        val baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
        val m = baos.toByteArray()
        val imageString = Base64.encodeToString(m,Base64.DEFAULT)



        //get form data from register layout
            jsonobject.put("FirstName", input_fname.text)
            jsonobject.put("LastName", input_lname.text)
            jsonobject.put("UserName", input_username.text)
            jsonobject.put("Phone", input_phone.text)
            jsonobject.put("DOB", input_DOB.text)
            jsonobject.put("Photo", imageString)
            jsonobject.put("Profile", input_profile.text)
            jsonobject.put("Email", input_email.text)
            jsonobject.put("Password", input_password.text)
            jsonobject.put("ConfirmPassword", input_confirm.text)

           var url = "https://elimination.azurewebsites.net/api/Account/Post"

            val que = Volley.newRequestQueue(this@Register)
            val req = JsonObjectRequest(Request.Method.POST, url, jsonobject,
                    Response.Listener<JSONObject>{
                        response -> response.toString()
                        //save PlayerID to val PlayerID
                        PlayerID  =  response.get("PlayerID").toString()
                        //save to sharedPreferences
                        val email = input_email.text.toString()
                        val mypref = getSharedPreferences(email, Context.MODE_PRIVATE)
                        val editor = mypref.edit()
                        editor.putString(email, PlayerID)
                        editor.apply()

                        val intent = Intent(this, Login::class.java)
                        startActivity(intent)
                    },
                    Response.ErrorListener{
                    response ->
                Log.e("Something went wrong", response.toString())
            })
        //if server is slow
        val socketTimeout = 30000 // 30 seconds
        val policy = DefaultRetryPolicy(socketTimeout,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)
        req.setRetryPolicy(policy)
        // Adding request to request queue
            que.add(req)
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)
        buttonLoadPicture.setOnClickListener(this)
        btn_register.setOnClickListener(this)
    }
}

1 个答案:

答案 0 :(得分:0)

    val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    startActivityForResult(intent, 1)

您在没有ACTION_IMAGE_CAPTURE的情况下调用EXTRA_OUTPUT

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        if (resultCode != RESULT_CANCELED) {
            if (requestCode == PICK_IMAGE_REQUEST) {

                val thumbnail = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath)
                PhotoImageView.setImageBitmap(thumbnail)

                filePath = getRealPathFromURI(Uri.parse(filePath.toString()))
            }
        }
    }

当您不提供Bitmap时,您没有使用从ACTION_IMAGE_CAPTURE返回的EXTRA_OUTPUT。相反,您正在查看可能filePath的{​​{1}}值,并且肯定与用户选择的相机应用可能拍摄的照片无关。

如果您想告诉相机应用在哪里放一张全尺寸照片,请使用null。但是,请记住,您不太可能将全尺寸照片转换为base64,因为内存不足。