无法打开捕获或图库选定的图像

时间:2018-01-09 06:25:17

标签: android image android-intent

我在图像(片段)上有2个按钮。一个用于使用相机捕获图像,另一个用于从库中选择。我可以捕捉图像并选择图像,但它没有打开新的活动。它再次开放相同的活动。并且还捕获未保存在我的新Directory中的图像。它创建目录但不保存图像。它保存在默认的相机文件夹中。

图像片段代码 - 有2个按钮

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
  //  return inflater.inflate(R.layout.fragment_images, container, false);
    View v = inflater.inflate(R.layout.fragment_images, container, false);
    FloatingActionButton btnCamera = (FloatingActionButton) v.findViewById(R.id.btnCamera);
    FloatingActionButton btnFolder = (FloatingActionButton) v.findViewById(R.id.btnFolder);

    btnCamera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            File imageFolder = new File(Environment.getExternalStorageDirectory(), "/My Children");
            imageFolder.mkdir();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
            String timestamp = simpleDateFormat.format(new Date());
            File image = new File(imageFolder, timestamp+ ".jpg");
            Uri uriImage = Uri.fromFile(image);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uriImage);
            startActivityForResult(intent, TAKE_PICTURE);
            }
    });
    btnFolder.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent, SELECT_PICTURE);
        }
    });
    return v;

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
  //  return inflater.inflate(R.layout.fragment_images, container, false);
    View v = inflater.inflate(R.layout.fragment_images, container, false);
    FloatingActionButton btnCamera = (FloatingActionButton) v.findViewById(R.id.btnCamera);
    FloatingActionButton btnFolder = (FloatingActionButton) v.findViewById(R.id.btnFolder);

    btnCamera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            File imageFolder = new File(Environment.getExternalStorageDirectory(), "/My Children");
            imageFolder.mkdir();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
            String timestamp = simpleDateFormat.format(new Date());
            File image = new File(imageFolder, timestamp+ ".jpg");
            Uri uriImage = Uri.fromFile(image);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uriImage);
            startActivityForResult(intent, TAKE_PICTURE);
            }
    });
    btnFolder.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent, SELECT_PICTURE);
        }
    });
    return v;

上传活动 - 我要在哪里展示图片

ImageView imageview = (ImageView) findViewById(R.id.imageview);
    Intent intent = getIntent();
    Bitmap bitmap = (Bitmap) intent.getParcelableExtra("image");
    imageview.setImageBitmap(bitmap);

logcat的

 E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.smiles.mychildren, PID: 5019
              android.os.FileUriExposedException: file:///storage/emulated/0/My%20Children/2018-19-09.jpg exposed beyond app through ClipData.Item.getUri()
                  at android.os.StrictMode.onFileUriExposed(StrictMode.java:1799)
                  at android.net.Uri.checkFileUriExposed(Uri.java:2346)
                  at android.content.ClipData.prepareToLeaveProcess(ClipData.java:832)
                  at android.content.Intent.prepareToLeaveProcess(Intent.java:8909)
                  at android.content.Intent.prepareToLeaveProcess(Intent.java:8894)
                  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1517)
                  at android.app.Activity.startActivityForResult(Activity.java:4224)
                  at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
                  at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
                  at android.support.v4.app.ActivityCompat.startActivityForResult(ActivityCompat.java:152)
                  at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:798)
                  at android.support.v4.app.FragmentActivity$HostCallbacks.onStartActivityFromFragment(FragmentActivity.java:907)
                  at android.support.v4.app.Fragment.startActivityForResult(Fragment.java:1028)
                  at android.support.v4.app.Fragment.startActivityForResult(Fragment.java:1017)
                  at com.smiles.mychildren.Images$1.onClick(Images.java:98)
                  at android.view.View.performClick(View.java:5609)
                  at android.view.View$PerformClick.run(View.java:22259)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

2 个答案:

答案 0 :(得分:0)

您在这里做错了,在startActivityForResult调用后添加参数。

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriImage);

只需更改此

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriImage);
startActivityForResult(intent, TAKE_PICTURE);

您也可以为图片捕获和从图库中选择图片设置相同的请求代码,您必须设置不同的请求代码。

您将RESULT_OKresultCode映射错误。只是改变这一点。

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == TAKE_PICTURE &&  resultCode== RESULT_OK){
            Bitmap bitmap = (Bitmap) data.getExtras().get("data");
            Intent i = new Intent(getActivity(), Upload.class);
            i.putExtra("image", bitmap);
            startActivity(i);
    }

  //TAKE_PICTURE(int 1) request code for camera capture
 //PICK_PICTURE_FROM_GALLERY (int 2) code for select image from gallery.

   if (requestCode == PICK_PICTURE_FROM_GALLERY &&  resultCode== RESULT_OK){
            Bitmap bitmap = (Bitmap) data.getExtras().get("data");
            Intent i = new Intent(getActivity(), Upload.class);
            i.putExtra("image", bitmap);
            startActivity(i);
    }
  }

答案 1 :(得分:0)

首先在permission -

上添加manifest.xml
 <uses-feature
        android:name="android.hardware.camera"
        android:required="true" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

使用相机拍摄图像

//capture image from camera
    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, ConstantCollection.REQUEST_IMAGE_CAPTURE);
        }
    }

使用Intent.ACTION_PICK作为Intent从图库中挑选图片 -

/pic image from   gallery
    private void pickImageFromGallery(){
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, ConstantCollection.REQUEST_IMAGE_GALLERY);
    }

并在OnActivityResult() -

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        //for camera capture
        if (requestCode == ConstantCollection.REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK && data != null) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            Intent i = new Intent(getActivity(), Upload.class);
            i.putExtra("image", imageBitmap );
            startActivity(i);
        }

        //for gallery
        if (requestCode == ConstantCollection.REQUEST_IMAGE_GALLERY && resultCode == RESULT_OK && data != null) {
            // Let's read picked image data - its URI
            Uri pickedImage = data.getData();
            // Let's read picked image path using content resolver
            String[] filePath = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
            cursor.moveToFirst();
            String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
            cursor.close();

            Intent i = new Intent(getActivity(), Upload.class);
            i.putExtra("image", bitmap);
            startActivity(i);
        }
    }