我正在编写一个小型程序,我想从相机中获取图片,将其显示在图像视图中(以后保存)。因此,我在按钮的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);
}
}
当我单击按钮时,Camera-App打开,我可以拍照。之后,我想在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);
}
我在做什么错? 帮助
答案 0 :(得分:0)
我认为您没有获得确切的图像路径。使用这个:
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);
答案 1 :(得分:0)
1-首先,您必须检查清单中是否具有权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
和功能:
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
如果您已经有了,可以按照我的示例进行操作,让我们以简单的方式进行。
2-假设您的活动中有一个ImageView和一个Button。 您将初始化组件并创建单击按钮功能。
private boolean isCamera = false;
private Uri fileUri;
private ImageView mImageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mImageView = layout.findViewById(R.id.mImageView);
Button mTakePhotoButton = layout.findViewById(R.id.mImageView);
mTakePhotoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final CharSequence[] items = {"Take photo", "Cancel"};
isCamera = false;
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
alertDialog.setTitle("Select Picture");
alertDialog.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
Intent intent;
switch (item) {
case CAMERA:
isCamera = true;
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getContext().getPackageManager()) != null) {
try {
File photoFile = Utils.createImageFile();
fileUri = Uri.fromFile(photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, 1);
} catch (IOException ex) {
Log.e("PROJECT_TEST", e.getMessage());
}
}
break;
/*case GALLERY:
intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, getString(R.string.select_picture)), imageBox);
break;*/
default:
dialog.dismiss();
break;
}
}
});
alertDialog.show();
}
});
}
我的 Utils.createImageFile ,该函数可在设备目录中创建文件:
public static File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "img_" + timeStamp + ".png";
File storageDir = new File(Environment.getExternalStorageDirectory(), "MyFolder");
if (!storageDir.exists())
storageDir.mkdirs();
return new File(storageDir, imageFileName);
}
3-您将在图像视图中以 onActivityResult
返回图像@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
Bitmap selectedImage;
if (!isCamera && data != null && data.getData() != null) {
fileUri = data.getData();
}
selectedImage = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), fileUri);
if (selectedImage != null) {
mImage1.setImageBitmap(selectedImage);
String directory = fileUri.toString();
Log.d("PROJECT_TEST", directory);
}
} catch (IOException e) {
e.printStackTrace();
Log.e("PROJECT_TEST", e.getMessage());
}
}
}
Obs:我正在使用Fragment,如果您正在使用活动,则可以将 getContext()更改为 this 。
答案 2 :(得分:0)
您的应用仅需要存储权限。请确保您拥有它-
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
创建文件夹时出现问题。
使用类似这样的内容:
path = new File(getExternalStorageDirectory()+ "/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);
mCurrentPhotoPath = image.getAbsolutePath();
startActivityForResult(cameraIntent, ACTION_REQUEST_CAMERA);
注意点:api 21中已弃用 inPurgeable