Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/314.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
Java 访问摄像头并存储棉花糖图像_Java_Android_Camera - Fatal编程技术网

Java 访问摄像头并存储棉花糖图像

Java 访问摄像头并存储棉花糖图像,java,android,camera,Java,Android,Camera,我有这个代码,允许用户访问相机拍照并从gallery中选择图像,它在运行Android 5.1.1的Sony Xperia Z3上运行 我现在已经升级到运行Android 6.0的Nexus 5X,但是当我尝试使用相机或保存图像时,我得到了任何帮助 我的代码使用照相机 Intent CameraImage = new Intent("android.media.action.IMAGE_CAPTURE"); Intent SelectedCameraImage = Intent.createCh

我有这个代码,允许用户访问相机拍照并从gallery中选择图像,它在运行Android 5.1.1的Sony Xperia Z3上运行

我现在已经升级到运行Android 6.0的Nexus 5X,但是当我尝试使用相机或保存图像时,我得到了任何帮助

我的代码使用照相机

Intent CameraImage = new Intent("android.media.action.IMAGE_CAPTURE");
Intent SelectedCameraImage = Intent.createChooser(CameraImage, "Take A Photo With");
startActivityForResult(SelectedCameraImage, SELECTED);
我的结果处理程序

public void onActivityResult(int RequestCode, int ResultCode, Intent Data) {
    if (ResultCode == RESULT_OK) {
        if (RequestCode == SELECTED) {
            Uri SelectedImageUri = Data.getData();
            SelectedImagePath = getPath(SelectedImageUri);
            Log.d("DatabaseOperations", "Image Path :  " + SelectedImagePath);
            Img.setImageURI(SelectedImageUri);

            try {
                FileInputStream FileInpStream = new FileInputStream(SelectedImagePath);
                BufferedInputStream BufInputStream = new BufferedInputStream(FileInpStream);
                DBByte = new byte[BufInputStream.available()];
                BufInputStream.read(DBByte);
                Log.d("DatabaseOperations", "Image Size :  " + DBByte.length + " KB");
            }

            catch (IOException e) {
                Log.d("DatabaseOperations", "Error :  " + SelectedImagePath);
                Log.d("DatabaseOperations", e.getMessage(), e);
            }
        }
    }
}

public String getPath(Uri Uris) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor Cursor = managedQuery(Uris, projection, null, null, null);
    int ColumnIndex = Cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    Cursor.moveToFirst();
    return Cursor.getString(ColumnIndex);
}
我的清单权限

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

<uses-permission-sdk-23 android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission-sdk-23 android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission-sdk-23 android:name="android.permission.CAMERA" />

首先,假设
Data.getData()
在这里是有意义的。您可以选择提供
EXTRA\u输出
(在这种情况下,图像应该在该EXTRA中指示的位置),或者从
Data.getExtra(“数据”)
获取缩略图。可能有一些摄像头应用程序返回
Uri
。但安卓设备有8000多种型号,有数百种(如果不是数千种的话)不同的默认摄像头应用程序。用户还可能让第三方摄像头应用程序处理您的请求。对于
Data.getData()
,大多数相机应用程序将为您提供
null

其次,即使您获得了
Uri
,您也假定
Uri
MediaStore
所知道的。这不是必需的

第三,即使您得到一个
Uri
,并且
MediaStore
知道它,您也假定
DATA
列是您可以访问的本地文件的路径。这不是必需的。例如,它可能是指向可移动存储的路径,您无法在Android 4.4+上访问该路径

要解决这三个问题,请使用
EXTRA_OUTPUT
指定相机存储图片的位置,并摆脱
getPath()
和对
Uri
的依赖

第四,在Android 6.0+上使用外部存储时,如果
targetSdkVersion
为23或更高,则需要请求
READ\u external\u storage
WRITE\u external\u storage
摄像机
权限也是如此


第五,不要对相同的权限使用
。在您的情况下,首先使用
,假设
Data.getData()
在这里是有意义的。您可以选择提供
EXTRA\u输出
(在这种情况下,图像应该在该EXTRA中指示的位置),或者从
Data.getExtra(“数据”)
获取缩略图。可能有一些摄像头应用程序返回
Uri
。但安卓设备有8000多种型号,有数百种(如果不是数千种的话)不同的默认摄像头应用程序。用户还可能让第三方摄像头应用程序处理您的请求。对于
Data.getData()
,大多数相机应用程序将为您提供
null

其次,即使您获得了
Uri
,您也假定
Uri
MediaStore
所知道的。这不是必需的

第三,即使您得到一个
Uri
,并且
MediaStore
知道它,您也假定
DATA
列是您可以访问的本地文件的路径。这不是必需的。例如,它可能是指向可移动存储的路径,您无法在Android 4.4+上访问该路径

要解决这三个问题,请使用
EXTRA_OUTPUT
指定相机存储图片的位置,并摆脱
getPath()
和对
Uri
的依赖

第四,在Android 6.0+上使用外部存储时,如果
targetSdkVersion
为23或更高,则需要请求
READ\u external\u storage
WRITE\u external\u storage
摄像机
权限也是如此


第五,不要对相同的权限使用
。在您的情况下,请使用

以下是我从相机或画廊拍摄图像的完整代码,它在棉花糖中与其他人一起工作很好

我在这里声明变量

protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_REQUEST = 1;
private static final int REQUEST_ACESS_STORAGE=3;
private static final int REQUEST_ACESS_CAMERA=2;
private Uri uri;
这里我有一些在棉花糖许可的方法

public static boolean checkPermission(String permission, Context context) {
    int statusCode = ContextCompat.checkSelfPermission(context, permission);
    return statusCode == PackageManager.PERMISSION_GRANTED;
}

public static void requestPermission(AppCompatActivity activity, String[] permission, int requestCode) {
    if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission[0])) {
        Toast.makeText(activity, "Application need permission", Toast.LENGTH_SHORT).show();
    }
    ActivityCompat.requestPermissions(activity, permission, requestCode);
}

public static void requestPermission(Fragment fragment, String[] permission, int requestCode) {
    fragment.requestPermissions(permission, requestCode);
}
我的onclick方法

if (v.getId()==R.id.idOfPhoto){
            handleCamera();
        }
手柄摄像方法的细节

private void handleCamera(){
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
            if (checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, this)) {
                startDilog();
            }else{
               requestPermission(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_ACESS_STORAGE);
            }
        }else{
            startDilog();
        }
    }
星图法

private void startDilog() {
    AlertDialog.Builder myAlertDilog = new AlertDialog.Builder(YourActivity.this);
    myAlertDilog.setTitle("Upload picture option..");
    myAlertDilog.setMessage("Where to upload picture????");
    myAlertDilog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Intent picIntent = new Intent(Intent.ACTION_GET_CONTENT,null);
            picIntent.setType("image/*");
            picIntent.putExtra("return_data",true);
            startActivityForResult(picIntent,GALLERY_REQUEST);
        }
    });
    myAlertDilog.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
                if(checkPermission(Manifest.permission.CAMERA,YourActivity.this)){
                    openCameraApplication();
                }else{
                    requestPermission(YourActivity.this,new String[]{Manifest.permission.CAMERA},REQUEST_ACESS_CAMERA);
                }
            }else{
                openCameraApplication();
            }
        }
    });
    myAlertDilog.show();
}
OpenCamera应用方法

private void openCameraApp() {
    Intent picIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (picIntent.resolveActivity(getPackageManager())!= null){
        startActivityForResult(picIntent, CAMERA_REQUEST);
    }
}
代码的其余部分

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == GALLERY_REQUEST) {
        if (resultCode == RESULT_OK) {
            if (data != null) {
                uri = data.getData();
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                try {
                    BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
                    options.inSampleSize =calculateInSampleSize(options, 100, 100);
                    options.inJustDecodeBounds = false;
                    Bitmap image = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
                    imageview.setImageBitmap(image);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(getApplicationContext(), "Cancelled",
                        Toast.LENGTH_SHORT).show();
            }
        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplicationContext(), "Cancelled",
                    Toast.LENGTH_SHORT).show();
        }
    } else if (requestCode == CAMERA_REQUEST) {
        if (resultCode == RESULT_OK) {
            if (data.hasExtra("data")) {
                Bitmap bitmap = (Bitmap) data.getExtras().get("data");
                uri = getImageUri(YourActivity.this, bitmap);
                File finalFile = new File(getRealPathFromUri(uri));
                imageview.setImageBitmap(bitmap);
            } else if (data.getExtras() == null) {

                Toast.makeText(getApplicationContext(),
                        "No extras to retrieve!", Toast.LENGTH_SHORT)
                        .show();

                BitmapDrawable thumbnail = new BitmapDrawable(
                        getResources(), data.getData().getPath());
                owner_pic.setImageDrawable(thumbnail);

            }

        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplicationContext(), "Cancelled",
                    Toast.LENGTH_SHORT).show();
        }
    }
}

private String getRealPathFromUri(Uri tempUri) {
    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = this.getContentResolver().query(tempUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}
private Uri getImageUri(YourActivity youractivity, Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    String path = MediaStore.Images.Media.insertImage(youractivity.getContentResolver(), bitmap, "Title", null);
    return Uri.parse(path);

public 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;
    }



@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(requestCode==REQUEST_ACESS_STORAGE && grantResults[0]== PackageManager.PERMISSION_GRANTED){
        startDilog();
    }
    if(requestCode==REQUEST_ACESS_CAMERA && grantResults[0]==PackageManager.PERMISSION_GRANTED){
        openCameraApp();
    }
}

它在所有设备中都能正常工作。

这是我从相机或画廊拍摄图像的完整代码,在棉花糖和其他设备中也能正常工作

我在这里声明变量

protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_REQUEST = 1;
private static final int REQUEST_ACESS_STORAGE=3;
private static final int REQUEST_ACESS_CAMERA=2;
private Uri uri;
这里我有一些在棉花糖许可的方法

public static boolean checkPermission(String permission, Context context) {
    int statusCode = ContextCompat.checkSelfPermission(context, permission);
    return statusCode == PackageManager.PERMISSION_GRANTED;
}

public static void requestPermission(AppCompatActivity activity, String[] permission, int requestCode) {
    if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission[0])) {
        Toast.makeText(activity, "Application need permission", Toast.LENGTH_SHORT).show();
    }
    ActivityCompat.requestPermissions(activity, permission, requestCode);
}

public static void requestPermission(Fragment fragment, String[] permission, int requestCode) {
    fragment.requestPermissions(permission, requestCode);
}
我的onclick方法

if (v.getId()==R.id.idOfPhoto){
            handleCamera();
        }
手柄摄像方法的细节

private void handleCamera(){
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
            if (checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, this)) {
                startDilog();
            }else{
               requestPermission(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_ACESS_STORAGE);
            }
        }else{
            startDilog();
        }
    }
星图法

private void startDilog() {
    AlertDialog.Builder myAlertDilog = new AlertDialog.Builder(YourActivity.this);
    myAlertDilog.setTitle("Upload picture option..");
    myAlertDilog.setMessage("Where to upload picture????");
    myAlertDilog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Intent picIntent = new Intent(Intent.ACTION_GET_CONTENT,null);
            picIntent.setType("image/*");
            picIntent.putExtra("return_data",true);
            startActivityForResult(picIntent,GALLERY_REQUEST);
        }
    });
    myAlertDilog.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
                if(checkPermission(Manifest.permission.CAMERA,YourActivity.this)){
                    openCameraApplication();
                }else{
                    requestPermission(YourActivity.this,new String[]{Manifest.permission.CAMERA},REQUEST_ACESS_CAMERA);
                }
            }else{
                openCameraApplication();
            }
        }
    });
    myAlertDilog.show();
}
OpenCamera应用方法

private void openCameraApp() {
    Intent picIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (picIntent.resolveActivity(getPackageManager())!= null){
        startActivityForResult(picIntent, CAMERA_REQUEST);
    }
}
代码的其余部分

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == GALLERY_REQUEST) {
        if (resultCode == RESULT_OK) {
            if (data != null) {
                uri = data.getData();
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                try {
                    BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
                    options.inSampleSize =calculateInSampleSize(options, 100, 100);
                    options.inJustDecodeBounds = false;
                    Bitmap image = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
                    imageview.setImageBitmap(image);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(getApplicationContext(), "Cancelled",
                        Toast.LENGTH_SHORT).show();
            }
        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplicationContext(), "Cancelled",
                    Toast.LENGTH_SHORT).show();
        }
    } else if (requestCode == CAMERA_REQUEST) {
        if (resultCode == RESULT_OK) {
            if (data.hasExtra("data")) {
                Bitmap bitmap = (Bitmap) data.getExtras().get("data");
                uri = getImageUri(YourActivity.this, bitmap);
                File finalFile = new File(getRealPathFromUri(uri));
                imageview.setImageBitmap(bitmap);
            } else if (data.getExtras() == null) {

                Toast.makeText(getApplicationContext(),
                        "No extras to retrieve!", Toast.LENGTH_SHORT)
                        .show();

                BitmapDrawable thumbnail = new BitmapDrawable(
                        getResources(), data.getData().getPath());
                owner_pic.setImageDrawable(thumbnail);

            }

        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplicationContext(), "Cancelled",
                    Toast.LENGTH_SHORT).show();
        }
    }
}

private String getRealPathFromUri(Uri tempUri) {
    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = this.getContentResolver().query(tempUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}
private Uri getImageUri(YourActivity youractivity, Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    String path = MediaStore.Images.Media.insertImage(youractivity.getContentResolver(), bitmap, "Title", null);
    return Uri.parse(path);

public 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;
    }



@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(requestCode==REQUEST_ACESS_STORAGE && grantResults[0]== PackageManager.PERMISSION_GRANTED){
        startDilog();
    }
    if(requestCode==REQUEST_ACESS_CAMERA && grantResults[0]==PackageManager.PERMISSION_GRANTED){
        openCameraApp();
    }
}

它在所有设备中都工作正常。

始终显示错误。它只是说对于图像存储/存储/模拟/0/Pictures/RajanDP.jpg:open failed:EACCES(权限被拒绝)您会遇到什么错误?您的
是否编译dkversion=23
?如果是这样,您需要确保您正在从ProcessRecord{c9f94d7 3768:rajancorporations.database/u0a80}(pid=3768,uid=10080)请求.and for the camera java.lang.SecurityException:权限拒绝:启动意图{act=android.media.action.IMAGE\u CAPTURE cmp=com.google.android.GoogleCamera/com.android.camera.CaptureActivity}对于撤销的权限,android.permission.CAMERAmy错误会显示在注释中,我正在API 23 max中生成,但API 22 min中生成。代码在API 22设备中正常,但在API 23设备上不正常始终显示错误。它只表示用于图像存储/存储/模拟/0/Pictures/RajanDP.jpg:打开失败:EACCES(权限被拒绝)你犯了什么错误?您的
是否编译dkversion=23
?如果是这样,您需要确保您正在从ProcessRecord{c9f94d7 3768:rajancorporations.database/u0a80}(pid=3768,uid=10080)请求.and for the camera java.lang.SecurityException:权限拒绝:启动意图{act=android.media.action.IMAGE\u CAPTURE cmp=com.google.android.GoogleCamera/com.android.camera.CaptureActivity}具有已撤销的权限android.permission.CAMERAmy