如何获取onActivityresult中图片的路径(Intent数据为空)

7

我需要启动相机,并在用户完成拍照后将其取出并显示在视图中。

参考 http://developer.android.com/guide/topics/media/camera.html,我已经完成了以下步骤:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bLaunchCamera = (Button) findViewById(R.id.launchCamera);
        bLaunchCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "lanzando camara");

                //create intent to launch camera
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                imageUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); //create a file to save the image
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); //set the image file name

                //start camera
                startActivityForResult(intent, CAMERA_REQUEST);
            }
        });

/**
     * Create a File Uri for saving image (can be sued to save video to)
     **/
    private Uri getOutputMediaFileUri(int mediaTypeImage) {
        return Uri.fromFile(getOutputMediaFile(mediaTypeImage));
    }

    /**
     * Create a File  for saving image (can be sued to save video to)
     **/
    private File getOutputMediaFile(int mediaType) {
        //To be safe, is necessary to check if SDCard is mounted

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                (String) getResources().getText(R.string.app_name));

        //create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(TAG, "failed to create directory");
                return null;
            }
        }

        //Create a media file name

        String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
        File mediaFile;

        if (mediaType == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");

        } else {
            return null;
        }
        return mediaFile;
    }

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == CAMERA_REQUEST) {
            if(resultCode == RESULT_OK) {
                //Image captured and saved to fileUri specified in Intent
                Toast.makeText(this, "image saved to:\n" + data.getData(), Toast.LENGTH_LONG).show();
                Log.d(TAG, "lanzando camara");
            } else if(resultCode == RESULT_CANCELED) {
                //user cancelled the image capture;
                Log.d(TAG, "usuario a cancelado la captura");
            } else {
                //image capture failed, advise user;
                Log.d(TAG, "algo a fallado");
            }
        }
    }

当图片完成后,应用程序尝试发送“Toast”信息时崩溃,因为“data”为空。

但是,如果我调试应用程序,我可以看到图像已保存。

enter image description here

所以我的问题是:我如何在onActivityResult中获取路径?
2个回答

3
您面临的问题是,每当我们从相机意图中选择图像时,它可能会结束调用它的活动,因此您创建的imageUri对象将在返回时为null。

所以当您退出活动(进入相机意图)时,需要保存它,像这样 -

    /**
     * Here we store the file url as it will be null after returning from camera
     * app
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // save file url in bundle as it will be null on screen orientation
        // changes
        outState.putParcelable("file_uri", mImageUri);
    }

并在您返回到活动时检索它 -
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        // get the file url
        mImageUri = savedInstanceState.getParcelable("file_uri");
    }

您的代码看起来很好,您只需要在其中添加此更改。


1
这里是我用于捕获和保存相机图像并将其显示到ImageView的代码。您可以根据需要使用它。
你必须将相机图像保存到特定位置,然后从该位置获取,然后将其转换为字节数组。
这是打开捕获相机图像活动的方法。
private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;

private void captureCameraImage() {
        Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
        chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        imageToUploadUri = Uri.fromFile(f);
        startActivityForResult(chooserIntent, CAMERA_PHOTO);
    }

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

            if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
                if(imageToUploadUri != null){
                    Uri selectedImage = imageToUploadUri;
                    getContentResolver().notifyChange(selectedImage, null);
                    Bitmap reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
                    if(reducedSizeBitmap != null){
                        ImgPhoto.setImageBitmap(reducedSizeBitmap);
                        Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
                          uploadImageButton.setVisibility(View.VISIBLE);                
                    }else{
                        Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                    }
                }else{
                    Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                }
            } 
        }

这里是在onActivityResult()中使用的getBitmap()方法。我已经尽可能地对获取相机拍摄图像位图进行了所有性能优化。
private Bitmap getBitmap(String path) {

        Uri uri = Uri.fromFile(new File(path));
        InputStream in = null;
        try {
            final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
            in = getContentResolver().openInputStream(uri);

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, o);
            in.close();


            int scale = 1;
            while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
                    IMAGE_MAX_SIZE) {
                scale++;
            }
            Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);

            Bitmap b = null;
            in = getContentResolver().openInputStream(uri);
            if (scale > 1) {
                scale--;
                // scale to max possible inSampleSize that still yields an image
                // larger than target
                o = new BitmapFactory.Options();
                o.inSampleSize = scale;
                b = BitmapFactory.decodeStream(in, null, o);

                // resize to desired dimensions
                int height = b.getHeight();
                int width = b.getWidth();
                Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);

                double y = Math.sqrt(IMAGE_MAX_SIZE
                        / (((double) width) / height));
                double x = (y / height) * width;

                Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
                        (int) y, true);
                b.recycle();
                b = scaledBitmap;

                System.gc();
            } else {
                b = BitmapFactory.decodeStream(in);
            }
            in.close();

            Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
                    b.getHeight());
            return b;
        } catch (IOException e) {
            Log.e("", e.getMessage(), e);
            return null;
        }
    }

我希望它有所帮助!


是的!我在这一行找到了解决问题的方法 --> if(imageToUploadUri != null){ Uri selectedImage = imageToUploadUri; 非常感谢! - Shudy
收到错误:java.lang.SecurityException:找不到用户0的提供程序;期望为此权限找到有效的ContentProvider。 - Asylzat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接