相机活动返回null android

时间:2011-08-08 12:33:28

标签: android android-camera

我正在构建一个应用程序,我希望通过默认的相机活动捕获图像并返回到我的活动并在ImageView中加载该图像。问题是相机活动总是返回null。在我的onActivityResult(int requestCode, int resultCode, Intent data)方法中,我获取的数据为null。这是我的代码:

public class CameraCapture extends Activity {

    protected boolean _taken = true;
    File sdImageMainDirectory;
    Uri outputFileUri;

    protected static final String PHOTO_TAKEN = "photo_taken";
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        try {

            super.onCreate(savedInstanceState);   
            setContentView(R.layout.cameracapturedimage);
                    File root = new File(Environment
                            .getExternalStorageDirectory()
                            + File.separator + "myDir" + File.separator);
                    root.mkdirs();
                    sdImageMainDirectory = new File(root, "myPicName");



                startCameraActivity();

        } catch (Exception e) {
            finish();
            Toast.makeText(this, "Error occured. Please try again later.",
                    Toast.LENGTH_SHORT).show();
        }

    }

    protected void startCameraActivity() {

        outputFileUri = Uri.fromFile(sdImageMainDirectory);

        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

        startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
    }

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

        switch (requestCode) {
        case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
        {
            if(resultCode==Activity.RESULT_OK)
            {
                try{
                ImageView imageView=(ImageView)findViewById(R.id.cameraImage);
                imageView.setImageBitmap((Bitmap) data.getExtras().get("data"));
                }
                catch (Exception e) {
                    // TODO: handle exception
                }
            }

            break;
        }

        default:
            break;
        }
    }

     @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState.getBoolean(CameraCapture.PHOTO_TAKEN)) {
            _taken = true;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean(CameraCapture.PHOTO_TAKEN, _taken);
    }
}

我做错了吗?

11 个答案:

答案 0 :(得分:102)

你错了,因为你做错了。

如果您使用相机意图传递额外参数MediaStore.EXTRA_OUTPUT,则相机活动会将捕获的图像写入该路径,并且不会以onActivityResult方法返回位图。

如果您要检查通过的路径,那么您将知道实际上相机已在该路径中写入捕获的文件。

有关详细信息,您可以关注thisthisthis

答案 1 :(得分:18)

我是以另一种方式做的。 data.getData()字段不保证返回一个Uri,所以我检查它是否为null,如果是,那么图像是额外的。所以代码是 -

if(data.getData()==null){
    bitmap = (Bitmap)data.getExtras().get("data");
}else{
    bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
}

我在生产应用程序中使用此代码,它正在运行。

答案 2 :(得分:6)

我有类似的问题。我在清单文件中注释掉了一些行,导致缩略图数据返回为空。

您需要以下内容才能使其正常工作:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

我希望这可以解决您的问题

如果您的手机是三星,则可能与此http://kevinpotgieter.wordpress.com/2011/03/30/null-intent-passed-back-on-samsung-galaxy-tab/

有关

还有另一个open question可能会提供更多信息

答案 3 :(得分:4)

如果您使用ImageView显示Camera Intent返回的位图 你需要在onSaveInstanceState中保存imageview引用,并在稍后的onRestoreInstanceState内部恢复它。查看下面的onSaveInstanceState和onRestoreInstanceState的代码。

public class MainActivity extends Activity {

    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;
    String mCurrentPhotoPath;
    ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        imageView = (ImageView) findViewById(R.id.imageView1);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void startCamera(View v) throws IOException {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File photoFile = null;

        photoFile = createImageFile();
        //intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
        }

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE
                && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            System.out.println(imageBitmap);
            imageView.setImageBitmap(imageBitmap);
        }
    }

    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(imageFileName, /* prefix */
                ".jpg", /* suffix */
                storageDir /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = "file:" + image.getAbsolutePath();
        System.out.println(mCurrentPhotoPath);
        return image;
    }

    private void setPic() {
        // Get the dimensions of the View
        int targetW = imageView.getWidth();
        int targetH = imageView.getHeight();

        // Get the dimensions of the bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;

        Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        imageView.setImageBitmap(bitmap);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        System.out.println(mCurrentPhotoPath);
        imageView = (ImageView) findViewById(R.id.imageView1);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onRestoreInstanceState(savedInstanceState);
        System.out.println(mCurrentPhotoPath);
        imageView = (ImageView) findViewById(R.id.imageView1);
    }
}

答案 4 :(得分:2)

经过多次搜索后:

private static final int TAKE_PHOTO_REQUEST = 1;
private ImageView mImageView;
String mCurrentPhotoPath;
private File photoFile;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_saisir_frais);
    mImageView = (ImageView) findViewById(R.id.imageViewPhoto);
    dispatchTakePictureIntent();
}





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

    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == TAKE_PHOTO_REQUEST && resultCode == RESULT_OK) {

            // set the dimensions of the image
            int targetW =100;
            int targetH = 100;

            // Get the dimensions of the bitmap
            BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            bmOptions.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(photoFile.getAbsolutePath(), bmOptions);
            int photoW = bmOptions.outWidth;
            int photoH = bmOptions.outHeight;

            // Determine how much to scale down the image
            int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

            // Decode the image file into a Bitmap sized to fill the View
            bmOptions.inJustDecodeBounds = false;
            bmOptions.inSampleSize = scaleFactor;
            bmOptions.inPurgeable = true;

           // stream = getContentResolver().openInputStream(data.getData());
            Bitmap bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath(),bmOptions);
            mImageView.setImageBitmap(bitmap);
    }

}


private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}


private void dispatchTakePictureIntent() {

    Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    try {
        photoFile = createImageFile();
        takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
        startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

答案 5 :(得分:1)

请尝试以下代码

            {
                final String[] imageColumns = { MediaStore.Images.Media._ID,MediaStore.Images.Media.DATA };

                final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
                Cursor imageCursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, null, null, imageOrderBy);
                imageCursor.moveToFirst();
                do {
                    String fullPath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    if (fullPath.contains("DCIM")) {

                        //get bitmap from fullpath here.
                        return;
                    }
                }
                while (imageCursor.moveToNext());

答案 6 :(得分:0)

您可以从发送到相机意图的文件生成位图。请使用此代码...

@Override

public void onActivityResult(int requestCode, int resultCode, Intent data){
    switch (requestCode) {

    case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
     {
        if(resultCode==Activity.RESULT_OK)
           {

                int orientation = getOrientationFromExif(sdImageMainDirectory);// get orientation that image taken

                BitmapFactory.Options options = new BitmapFactory.Options();

                InputStream is = null;
                Matrix m = new Matrix();
                m.postRotate(orientation);//rotate image

                is = new FileInputStream(sdImageMainDirectory);

                options.inSampleSize = 4 //(original_image_size/4);
                Bitmap bitmap = BitmapFactory.decodeStream(is,null,options);
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                        bitmap.getHeight(), m, true);

                 // set bitmap to image view    

                 //bitmap.recycle();    
           }

        break;
    }

    default:
        break;
    }

}

private int getOrientationFromExif(String imagePath) {
        int orientation = -1;
        try {
            ExifInterface exif = new ExifInterface(imagePath);
            int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 
                    ExifInterface.ORIENTATION_NORMAL);

            switch (exifOrientation) {
                case ExifInterface.ORIENTATION_ROTATE_270:
                    orientation = 270;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    orientation = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_90:
                    orientation = 90;
                    break;
                case ExifInterface.ORIENTATION_NORMAL:
                    orientation = 0;
                    break;
                default:
                    break;
            }
        } catch (IOException e) {
            //Log.e(LOG_TAG, "Unable to get image exif orientation", e);
        }
        return orientation;
    }

答案 7 :(得分:0)

File cameraFile = null;

public void openChooser() {
    Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    cameraFile = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
    takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));

    String pickTitle = "Select or take a new Picture"; // Or get from strings.xml
    Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,new Intent[]{takePhotoIntent});
    startActivityForResult(chooserIntent, SELECT_PHOTO);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case SELECT_PHOTO:
            if (resultCode == Activity.RESULT_OK) {
                Uri selectedImage = data.getData();
                if (selectedImage != null) {
                    //from gallery 
                } else if (cameraFile != null) {
                    //from camera
                    Uri cameraPictureUri = Uri.fromFile(cameraFile);
                }
            }
            break;
    }
}

答案 8 :(得分:0)

试试本教程。它适用于我,并在宣言和照片中使用许可。也 检查权限

https://androidkennel.org/android-camera-access-tutorial/

答案 9 :(得分:0)

经过大量的研究,我终于得出了结论。 为此,您应该将捕获的图像保存到外部存储器。 然后,在上传时检索。 这样,图像分辨率不会降低,您也不会得到NullPointerException! 我使用时间戳来命名文件,因此每次都获得唯一的文件名。

<string name="DetailsOfWiFiDef">The WiFi status is ${myObject.status},
        the name of WiFi is ${myObject.name}\n\n
</string>

val myObject=getIt()
val s=mContext.getString(R.string.DetailsOfWiFiDef)
val sb = StringBuilder()
sb.append(s)  //The string keep original

创建文件名的功能:

val myObject=getIt()
val k="The WiFi status is ${myObject.status},the name of WiFi is ${myObject.name} \n"
val sb = StringBuilder()
sb.append(k)  //It has been replaced         

和onActivityResult:

 private void fileChooser2() {
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
    Intent intent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    String pictureName=getPictureName();
    fi=pictureName;
    File imageFile=new File(pictureDirectory,pictureName);
    Uri pictureUri = Uri.fromFile(imageFile);
    intent.putExtra(MediaStore.EXTRA_OUTPUT,pictureUri);
    startActivityForResult(intent,PICK_IMAGE_REQUEST2);
}

希望这会有所帮助:)

编辑:授予摄像机权限以及清单中存储的写入和读取权限。

答案 10 :(得分:0)

从相机取景时,很少有手机返回null。下面的解决方法将解决。确保检查数据是否为空。

          private int  CAMERA_NEW = 2;
          private String imgPath;

          private void takePhotoFromCamera() {
               Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
               intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
               startActivityForResult(intent, CAMERA_NEW);
          }

         // to get the file path 
         private  Uri setImageUri() {
           // Store image in dcim
              File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
              Uri imgUri = Uri.fromFile(file);
              this.imgPath = file.getAbsolutePath();
              return imgUri;
           }
          
          @Override
          public void onActivityResult(int requestCode, int resultCode, Intent data) 
          {
                 super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == CAMERA_NEW) {

              try {
                 Log.i("Crash","CAMERA_NEW");
                 if(data!=null &&(Bitmap) data.getExtras().get("data")!=null){
                     bitmap = (Bitmap) data.getExtras().get("data");
                     personImage.setImageBitmap(bitmap);
                     Utils.saveImage(bitmap, getActivity());
                               
                 }else{
                       File f= new File(imgPath);
                       BitmapFactory.Options options = new BitmapFactory.Options();
                       options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                       options.inSampleSize= 4;
                       bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
                       personImage.setImageBitmap(bitmap);
                              
                    }
                } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "Failed!", Toast.LENGTH_SHORT).show();
             }
      }