在我的应用中获取相机拍摄的图像时出现问题。
当我尝试获取文件时,它不存在。我看不出问题出在哪里:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Uri uri = Uri.parse("/sdcard/Images/test_image.jpg");
Intent photoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photoIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
File image=new File("/sdcard/Images/","test_image.jpg");
if (image.exists()){
Bitmap bm = BitmapFactory.decodeFile("/sdcard/Images/test_image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
}
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
当到达image.exists()时,它表示为false。我已经在清单上写了sd写权限。
Uri.parse创建一个uri,它解析给定的编码URI字符串,而不是sdcard上不存在的文件路径。因此,无论是用户"file://"+ filename_with_path
还是使用Uri.fromFile从文件路径创建URI。还使用Environment.getExternalStorageDirectory()
代替sdcard的静态路径作为:
File dir = Environment.getExternalStorageDirectory();
file = new File(dir, "test_image.jpg");
Uri uri = Uri.fromFile(file);
Intent photoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photoIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(photoIntent, CAMERA_REQUEST);
第二个大问题是你逝去的cameraIntent
意图在其中您不添加MediaStore.EXTRA_OUTPUT
到startActivityForResult
。因此将photoIntent传递给startActivityForResult,因为您是在photoIntent Intent实例中而不是在MediaIntent Intent实例中添加MediaStore.EXTRA_OUTPUT键cameraIntent
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句