gpt4 book ai didi

android - 文件不存在相机拍摄的android图像

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:48:35 26 4
gpt4 key购买 nike

在我的应用中获取相机拍摄的图像时遇到问题。

当我尝试获取文件时,它不存在。我看不出问题出在哪里:

@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。我已经在 list 上写了 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 Intent ,其中您没有将 MediaStore.EXTRA_OUTPUT 添加到 startActivityForResult。所以将 photoIntent 传递给 startActivityForResult 因为您在 photoIntent Intent 实例中添加 MediaStore.EXTRA_OUTPUT 键而不是 cameraIntent

关于android - 文件不存在相机拍摄的android图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21984570/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com