从相机意图上传

时间:2018-07-18 12:50:52

标签: android imageview android-camera

目前正在研究小型应用程序以自我介绍。我需要捕获图像,在imageview上显示它并上传它。我已经设法创建了该意图并在imageview上显示了图像,但目前无法上传它,也无法弄清楚该怎么办?也有从图库上传图像的按钮。我应该使用Asynctask吗?我迷路了

相机意图:

mCapture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent cameraIntent = new Intent (MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, REQUEST_CAMERA_CAPTURE);
        }
    });

图片上传:

private void UploadImage (){

    StringRequest stringRequest = new StringRequest(Request.Method.POST, UploadUrl,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String Response = jsonObject.getString("response");
                        Toast.makeText(MainActivity.this,Response,Toast.LENGTH_SHORT).show();
                        mImageView.setImageResource(0);
                        mImageView.setVisibility(View.GONE);
                        mEditText.setText("");
                        mEditText.setVisibility(View.GONE);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    })


    {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params = new HashMap<>();
            params.put("name1",mEditText.getText().toString().trim());
            params.put("name2", staticSpinner.getSelectedItem().toString().trim());
            params.put("image",ImageToString(bitmap));

            return params;
        }
    };

图片到字符串

    private String ImageToString(Bitmap bitmap){

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 25, byteArrayOutputStream);
    byte [] imgBytes = byteArrayOutputStream.toByteArray();

    return Base64.encodeToString(imgBytes, Base64.DEFAULT);
}

1 个答案:

答案 0 :(得分:0)

您应该上传图像的字节数组,下面是将位图转换为字节数组的代码。

Bitmap bmp = intent.getExtras().get("data"); // your image bitmap
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();  send this b
bmp.recycle(); // recycle your bitmap