当我尝试拍摄照片并从onActivityResult()获取时,我的Android应用程序出现问题。我想确保代码能够正常运行,因此我刚刚复制了此页面的确切代码http://developer.android.com/training/camera/photobasics.html。
所以这些是我使用的方法;当用户点击按钮时,我调用dispatchTakePictureIntent()。
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
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(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, 15);
}
}
}`
问题是当调用onActivityResult()方法时,我得到正确的requestCode,正确的resultCode,但第三个参数为null。我想获取图像Bitmap或Path,但我不能没有它。为什么会这样?是因为这段代码不应该返回该参数吗?在那种情况下,我应该如何修改它?
答案 0 :(得分:0)
尝试此代码测试。
拍照
private void TakePicture(){
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
}
保存到文件
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if (resultCode == Activity.RESULT_OK) {
try{
String filename = "name.jpg";
File sd = Environment.getExternalStorageDirectory();
File dest = new File(sd, filename);
Bitmap bp = (Bitmap) data.getExtras().get("data");
FileOutputStream out = new FileOutputStream(dest);
bp.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
//
} catch (Exception e) {
Toast.makeText(this, "Failed", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
}
}
答案 1 :(得分:0)
仅当您在拍照后未指定用于保存图像的文件URI时,才会收到onActivityResult()
中的缩略图图像。如果要接收预览图像,请从代码中删除此行:
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));