用相机意图拍照并将其保存到文件
问题描述:
我正在尝试让我的应用启动相机意图以拍摄照片并将其保存到目录中,并在主视图中显示缩略图,但是我似乎不太正确。这是我使用的方法:
I'm trying to get my app to start a camera intent in order to take a picture and save it into a directory as well as show a thumbnail in the main view, but I don't quite seem to get it right. Here's the methods I'm using:
@RequiresApi(api = Build.VERSION_CODES.M)
private void dispatchTakePictureIntent() {
if (ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.CAMERA},
5);
}
}
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getContext().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
if(photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getContext(),
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
这是 OnActivityResult
:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
image.setImageBitmap(imageBitmap);
}
}
我似乎收到了 NullPointerException 在两个不同的位置,
I seem to be getting a NullPointerException
in two different places, at:
-
photoFile。 createNewFile();
-
image.setImageBitmap(imageBitmap);
photoFile.createNewFile();
image.setImageBitmap(imageBitmap);
我该如何解决?
答
更改您的 onActivityResult
到
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
onCaptureImageResult(data);
}
}
用于在缩略图中设置 ImageView 中的c> data :
for setting in a thumbnail pass the data
in your ImageView
variable like this:
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
byteArray = bytes.toByteArray();
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imageView.setImageBitmap(thumbnail);
}