Android Studio 3.6.3-拍照时出现相机错误:打开失败:ENOENT(没有这样的文件或目录)



由于我已将Android Studio更新到3.6.3,因此无法在onActivityResult()函数中获取照片。我使用的是Android 8的三星手机,存储相机权限设置为允许。

这是我的代码:

int CAMERA = 0;
int GALLERY = 1;
Uri imageURI;
File file;
public void openCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = new File(Environment.getExternalStorageDirectory(), "image.jpg");
imageURI = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".provider", file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageURI);
startActivityForResult(intent, CAMERA);
}

// onActivityResult
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
Bitmap bmp;
// • IMAGE FROM CAMERA
if (requestCode == CAMERA) {
try {
File f = file;
ExifInterface exif = new ExifInterface(f.getPath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int angle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) { angle = 90;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) { angle = 180;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) { angle = 270; }
Matrix mat = new Matrix();
mat.postRotate(angle);
bmp = BitmapFactory.decodeStream(new FileInputStream(f), null, null);
assert bmp != null;
bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mat, true);
bmp = scaleBitmapToMaxSize(800, bmp);
myImgView.setImageBitmap(bmp);
// error
} catch (IOException | OutOfMemoryError e) { Log.i("log-", "ERROR: " + e.getMessage()); }
}
}// ./ If RESULT_OK
}

// Scale image
public static Bitmap scaleBitmapToMaxSize(int maxSize, Bitmap bm) {
int outWidth;
int outHeight;
int inWidth = bm.getWidth();
int inHeight = bm.getHeight();
if (inWidth > inHeight) {
outWidth = maxSize;
outHeight = (inHeight * maxSize) / inWidth;
} else {
outHeight = maxSize;
outWidth = (inWidth * maxSize) / inHeight;
}
return Bitmap.createScaledBitmap(bm, outWidth, outHeight, false);
}

清单:

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

拍照后,我在Logcat中得到了这个错误,当然,myImgView:中不会显示任何图片

ERROR: /storage/emulated/0/image.jpg: open failed: ENOENT (No such file or directory)

我该怎么解决这个问题?

我通过使用一行代码找到了一个解决方案,它似乎是临时的,但到目前为止,它在Android 10设备上可以工作。

只需在Manifest.xml文件的<application标记中添加此行:

android:requestLegacyExternalStorage="true" 

这将允许应用程序将内部存储中的图片和视频保存到具有项目包名称的文件夹中。

相关内容

最新更新