Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/200.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
摄像头活动返回空android_Android_Android Camera - Fatal编程技术网

摄像头活动返回空android

摄像头活动返回空android,android,android-camera,Android,Android Camera,我正在构建一个应用程序,在该应用程序中,我希望通过默认相机活动捕获图像,然后返回到我的活动,并将该图像加载到ImageView中。问题是摄影机活动始终返回null。在我的onActivityResult(int-requestCode,int-resultCode,Intent-data)方法中,我获取的数据为null。这是我的密码: public class CameraCapture extends Activity { protected boolean _taken = tru

我正在构建一个应用程序,在该应用程序中,我希望通过默认相机活动捕获图像,然后返回到我的活动,并将该图像加载到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);
    }
}

我做错什么了吗?

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

要使其正常工作,您需要以下各项:

<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" />

我希望这能解决你的问题

如果你的手机是三星,它可能与此有关


还有一种可能会提供额外的信息

因为你做得不对,所以你错了

如果将额外参数
MediaStore.extra_OUTPUT
与摄像机意图一起传递,摄像机活动将把捕获的图像写入该路径,并且不会在
onActivityResult
方法中返回位图

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


有关更多信息,您可以按照下面的说明进行操作,我正在以另一种方式进行操作。data.getData()字段不保证返回Uri,因此我正在检查它是否为null,如果为null,则图像在附加中。因此,守则是—

if(data.getData()==null){
    bitmap = (Bitmap)data.getExtras().get("data");
}else{
    bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
}
我在生产应用程序中使用了这段代码,它正在工作。

如果您使用ImageView显示相机返回的位图 您需要将imageview引用保存在onSaveInstanceState中,并在以后的onRestoreInstanceState中还原它。查看下面onSaveInstanceState和onRestoreInstanceState的代码


您可以从发送到camera intent的文件生成位图。请使用此代码

@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;
    }
尝试以下代码

经过多次搜索:

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();
    }
}

试试这个教程。它对我有效,并且像往常一样在宣言中使用许可&也是 检查权限


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

 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);
}
函数创建文件名:

private String getPictureName() {
    SimpleDateFormat adf=new SimpleDateFormat("yyyyMMdd_HHmmss");
    String timestamp = adf.format(new Date());
    return "The New image"+timestamp+".jpg";//give a unique string so that the imagename cant be overlapped with other apps'image formats
}
以及onActivityResult:

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

        if(requestCode==PICK_IMAGE_REQUEST2 && resultCode==RESULT_OK )//&& data!=null && data.getData()!=null)
        {
            final ProgressDialog progressDialog = new ProgressDialog(this);
            progressDialog.setTitle("Uploading");
            progressDialog.show();
            Toast.makeText(getApplicationContext(),"2",Toast.LENGTH_SHORT).show();
                File picDir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            File imageFile=new File(picDir.getAbsoluteFile(),fi);
            filePath=Uri.fromFile(imageFile);
            try {
            }catch (Exception e)
            {
                e.printStackTrace();
            }



            StorageReference riversRef = storageReference.child(mAuth.getCurrentUser().getUid()+"/2");
            riversRef.putFile(filePath)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    })
                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                            double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                            progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
                        }
                    });
@覆盖
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
if(requestCode==PICK\u IMAGE\u REQUEST2&&resultCode==RESULT\u OK)/&&data!=null&&data.getData()!=null)
{
final ProgressDialog ProgressDialog=新建ProgressDialog(此);
progressDialog.setTitle(“上传”);
progressDialog.show();
Toast.makeText(getApplicationContext(),“2”,Toast.LENGTH_SHORT.show();
文件picDir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY\u图片);
File imageFile=新文件(picDir.getAbsoluteFile(),fi);
filePath=Uri.fromFile(imageFile);
试一试{
}捕获(例外e)
{
e、 printStackTrace();
}
storagereferef=StorageReference.child(mAuth.getCurrentUser().getUid()+“/2”);
riversRef.putFile(文件路径)
.addOnSuccessListener(新的OnSuccessListener(){
@凌驾
成功时公共无效(UploadTask.TaskSnapshot TaskSnapshot){
progressDialog.disclose();
Toast.makeText(getApplicationContext(),“上传文件”,Toast.LENGTH_LONG.show();
}
})
.addOnFailureListener(新的OnFailureListener(){
@凌驾
public void onFailure(@NonNull异常){
progressDialog.disclose();
Toast.makeText(getApplicationContext(),exception.getMessage(),Toast.LENGTH_LONG.show();
}
})
.addOnProgressListener(新的OnProgressListener(){
@凌驾
public void onProgress(UploadTask.TaskSnapshot TaskSnapshot){
双进度=(100.0*taskSnapshot.GetByTestTransferred())/taskSnapshot.getTotalByteCount();
setMessage(“上传的”+((int)进度)+“%…”;
}
});
希望这有帮助:)


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

从摄像头读取时,少数手机将返回null。下面的解决方法将解决此问题。请确保检查数据是否为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();
             }
      }

SD卡是否已安装?您可以在哪里看到图像“myPicName”?您在清单中有权限吗?我可以在usb调试时在ddms中看到该文件。我也已授予该权限。如果在imageview中加载图像时使用outputFileUri而不是数据,则可以正常工作。这意味着相机正在捕获图像,但为什么我会被捕获在onactivityresult()的数据参数中设置null方法如果你允许访问你的存储,请注意。我也有同样的问题,我担心这些权限不会改变任何事情。至少对我来说,似乎没有解决办法。我已经搜索了好几天,为什么会是这样?我非常沮丧,因为我不能用应用程序拍摄一张照片。@cubsink是我吗t三星…?很抱歉最近的回复@Merlin。但是是的,它是三星的设备。那是一年多以前的事了,我想现在情况已经改变了。@cubsink,ach it wa
private String getPictureName() {
    SimpleDateFormat adf=new SimpleDateFormat("yyyyMMdd_HHmmss");
    String timestamp = adf.format(new Date());
    return "The New image"+timestamp+".jpg";//give a unique string so that the imagename cant be overlapped with other apps'image formats
}
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==PICK_IMAGE_REQUEST2 && resultCode==RESULT_OK )//&& data!=null && data.getData()!=null)
        {
            final ProgressDialog progressDialog = new ProgressDialog(this);
            progressDialog.setTitle("Uploading");
            progressDialog.show();
            Toast.makeText(getApplicationContext(),"2",Toast.LENGTH_SHORT).show();
                File picDir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            File imageFile=new File(picDir.getAbsoluteFile(),fi);
            filePath=Uri.fromFile(imageFile);
            try {
            }catch (Exception e)
            {
                e.printStackTrace();
            }



            StorageReference riversRef = storageReference.child(mAuth.getCurrentUser().getUid()+"/2");
            riversRef.putFile(filePath)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    })
                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                            double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                            progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
                        }
                    });
          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();
             }
      }