从相机捕获图像时,位图为空

时间:2019-04-19 01:20:55

标签: java android bitmap android-bitmap

我的代码在API级别<= 19上运行良好,但在更高版本中,位图为空。

public void SelectImage() {
        final CharSequence[] items = {"Camera", "Gallery", "Cancel"};

        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.add_image);
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int i) {
                if (items[i].equals("Camera")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (intent.resolveActivity(mainActivity.getPackageManager()) != null) {
                        startActivityForResult(intent, REQUEST_CAMERA);
                    }
                } else if (items[i].equals("Gallery")) {
                    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(intent, SELECT_FILE);

                } else if (items[i].equals("Cancel")) {
                    dialog.dismiss();
                }

            }
        });


public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PLACE_PICKER_REQUEST) {
            if (resultCode == RESULT_OK) {
                place = PlacePicker.getPlace(data, mainActivity);
                etAddress1.setText(place.getAddress());
            }
        } else if (resultCode == Activity.RESULT_OK && data != null) {

            Glide.with(this).load(data.getData()).into(ivprofile);
            Bitmap bm = null;
            try {
                bm = MediaStore.Images.Media.getBitmap(mainActivity.getContentResolver(), data.getData());
            } catch (IOException e) {
                e.printStackTrace();
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.JPEG, 50, baos);
            byte[] b = baos.toByteArray();
            base64img = Base64.encodeToString(b, Base64.NO_WRAP);
        }
    }

在这里,我的bm为null,这是为什么我使用较旧的代码版本还是有其他问题。.预先感谢。

1 个答案:

答案 0 :(得分:0)

实际上,有一个库适用于每部手机和所有android版本。如果您需要解决问题,这里是一个答案。 EasyImage完成了工作!

不要忘记处理api 23及更高版本的权限!