首页 文章

Android - 前置摄像头错误

提问于
浏览
0

我正在尝试捕获图像,但在捕获和批准后, onActivityResult(int requestCode, int resultCode, Intent data) data 始终为空 .

这就是我给相机打电话的方式:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, getImageUri());
startActivityForResult(intent, Consts.ACTION_JOURNEY_CAPTURE_PHOTO_PATH);

方法getImageUri():

private Uri getImageUri() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "IMG_" + timeStamp + "_";
        File albumF = helpers.getAlbumDir(getString(R.string.album_name));

        File file = new File(albumF, imageFileName);
        Uri imgUri = Uri.fromFile(file);

        return imgUri;
}

在清单上我有:

<uses-feature android:name="android.hardware.camera" />

我究竟做错了什么?

1 回答

  • 1

    图像存储在使用getImageUri()方法获得的路径中 . 您必须保留该路径,并在onActivityResult()内部执行以下操作:

    if (resultCode == RESULT_OK) {
    
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(photoPath, options);
    
            Bitmap b = BitmapFactory.decodeFile(photoPath, options);
    
        }
    

    如果要调整图像大小,可以设置BitmapFactory.Options的inSampleSize,此方法对于计算inSampleSize非常有用:

    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
            // Raw height and width of image
            final int height = options.outHeight;
            final int width = options.outWidth;
            int inSampleSize = 1;
    
            if (height > reqHeight || width > reqWidth) {
    
                final int halfHeight = height / 2;
                final int halfWidth = width / 2;
    
                // Calculate the largest inSampleSize value that is a power of 2 and keeps both
                // height and width larger than the requested height and width.
                while ((halfHeight / inSampleSize) > reqHeight
                        && (halfWidth / inSampleSize) > reqWidth) {
                    inSampleSize *= 2;
                }
            }
    
            return inSampleSize;
        }
    

相关问题