android - 为什么我没有从我的相机意图中收到任何图片(在 Android 中)
问题描述
我正在编写一个小程序,我想从我的相机中获取一张图片,将其显示在图像视图中(并稍后保存)。因此,我在按钮的 onclick-Method 中创建了一个 Intent:
File path;
@Override
public void onClick(View v) {
path = new File(getFilesDir(), "Gallery/MyImages/");
if (!path.exists()) path.mkdirs();
File image = new File(path, "image_capture.jpg");
Uri imageUri = FileProvider.getUriForFile(getApplicationContext(), CAPTURE_IMAGE_FILE_PROVIDER, image);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
providePermissionForProvider(cameraIntent, imageUri);
mCurrentPhotoPath = image.getAbsolutePath();
startActivityForResult(cameraIntent, ACTION_REQUEST_CAMERA);
}
private void providePermissionForProvider(Intent intent, Uri uri) {
List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
当我点击按钮时,相机应用程序打开,我可以拍照。之后,我想在 onActivityResult-Method 中的 Bitmap 中获取这张图片。但它不起作用:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
int targetW = main.getWidth();
int targetH = main.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);
Log.d("Facee", "afdadsfafdasfsfsfdsafdsafsdfdsafdsafdsafdsadsafdsadsf");
main.setImageBitmap(bitmap);
}
我究竟做错了什么?帮助
解决方案
我认为您没有获得图像的确切路径。用这个:
File tempFile = File.createTempFile("camera", ".png", getExternalCacheDir());
mPath = tempFile.getAbsolutePath();
Uri uri = Uri.fromFile(tempFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
推荐阅读
- reactjs - React Redux 使用来自 API 的新数据更新 UI,无需用户输入
- html - 如何在行布局中包装 flexbox 的内容?
- python - 按 id 过滤 TensorFlow 数据集
- python - 如何以相反的顺序获取numpy多维数组的索引?
- python - 如何根据列值和行值连接两个df?
- c# - C# utf 字符串转换,无法正确显示的字符被转换为“未知字符” - 如何防止这种情况?
- go - 如何在此 Go 频道为空之前取消订阅?
- python - 如何将函数添加到 eval 函数的全局列表中?
- java - 将spring boot lib文件夹移到jar之外
- java - 移动没有窗口标题栏的 JFrame