【发布时间】:2016-05-06 16:47:40
【问题描述】:
我正在尝试使用本机设备相机拍照。我从发送意图开始:
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getMainActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
相机启动,文件创建,我正在拍照,然后这张照片被接收并使用以下代码解码:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
if (bitmap == null) {
Crashlytics.log("Bitmap factory returned null");
}
mImageCropper.setBitmapPhoto(bitmap);
expand(mMainImage);
}
}
这是创建文件并记住它的路径的方法:
private File createImageFile() throws IOException {
// Create an image file name
@SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
if (!image.exists()) {
Log.e("take photo", "can't create photo file");
Crashlytics.logException(new NullPointerException("Can't read photo from camera"));
} else {
Log.d("take photo", "photo file created " + image.getPath());
}
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
但有时我在解码此位图时出错:
D/skia: --- SkImageDecoder::Factory returned null
当我重新启动设备(Nexus 5 (6.0 Marshmallow),但它也发生在其他设备上)时,此过程的第一次运行正常,但随后开始出现错误。我无法在 genymotion 模拟器(Nexus 5、5.0)上重现此错误
更新 - 原因和解决方法
似乎原生安卓相机应用程序在位图完全写入持久存储之前返回它的结果。我并不引以为豪的代码,但它仍然有效:
final Handler handler = new Handler();
@Override
public void onActivityResult(final int requestCode, final int resultCode, Intent data) {
Runnable decodeRunnable = new Runnable() {
int counter = 0;
@Override
public void run() {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
if (bitmap == null && counter < 20) {
handler.postDelayed(this, 200);
}
mImageCropper.setBitmapPhoto(bitmap);
expand(mMainImage);
}
}
};
handler.postDelayed(decodeRunnable, 100);
}
如您所见,此方法将尝试解码位图最多 20 次,尝试之间有 200 毫秒的中断。如果您有更好的想法,我们将不胜感激。
【问题讨论】:
-
mCurrentPhotoPath似乎与您创建图片的方式没有任何关系。mCurrentPhotoPath到底是什么? -
我添加了缺失的代码片段 - createImageFile() 方法
-
您是否通过
onSaveInstanceState()保留此值?请记住,当用户选择的相机应用程序在前台时,您的进程可能会终止。 -
这不是原因 - 文件路径与创建时完全相同。
-
@CommonsWare 感谢您尝试帮助我 - 我认为这对您来说会很有趣,马克。
标签: android