嗨我需要从相机拍照并在屏幕上显示。
但我将Uri视为无效。
我需要获取文件的绝对路径。
我的代码:
mintent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
mintent.putExtra(MediaStore.EXTRA_OUTPUT,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
startActivityForResult(mintent, 1);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((data != null && !data.toString().equalsIgnoreCase("Intent { }"))
|| requestCode == 1)
switch (requestCode) {
case 1:
try {
Uri imageFileUri = data.getData();
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
img2.setImageBitmap(bitmap);
}
}
请帮助..
答案 0 :(得分:1)
你的问题在这里:
mintent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
mintent.putExtra(MediaStore.EXTRA_OUTPUT,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
您没有在您希望文件驻留的位置传递URI。而是传递文件夹的URI。您应该将URI传递到您希望文件的位置。这是我几个月前做过的一个项目的例子:
File lastSavedFile;
/**
* IMPORTANT: this must be a directory readable by multiple apps (not private storage)
* @return
*/
@SuppressLint("SimpleDateFormat")
private File getTempFile() {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "barfile_" + timeStamp + ".jpg";
return new File(Environment.getExternalStorageDirectory(), imageFileName);
}
/**
* Called when we want to take a picture
*
* @param position
*/
private void launchTakePictureIntent(int position)
{
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
lastSavedFile = getTempFile();
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(lastSavedFile));
startActivityForResult(i, position);
}
/**
* Returns from the camera intent, hopefully with a picture
*/
@Override
protected void onActivityResult(int position, int resultCode, Intent intent) {
super.onActivityResult(position, resultCode, intent);
if (resultCode == RESULT_OK) {
Uri imageUri = Uri.fromFile(lastSavedFile);
Bitmap fullBitmap;
try {
fullBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (Exception e) {
Log.e(TAG, e.toString(), e);
return;
}
...
答案 1 :(得分:0)
这是我用来获取图片的Uri的代码。
private Bitmap photo;
private File pic;
private Uri uri;
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
photo = (Bitmap) data.getExtras().get("data");
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()) {
pic = new File(root, "pic.png");
FileOutputStream out = new FileOutputStream(pic);
photo.compress(CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
} catch (IOException e) {
Log.e("BROKEN", "Could not write file " + e.getMessage());
}
// This is the uri you are looking for.
uri = Uri.fromFile(pic);
}
}
PS:不要忘记接受上一个问题的答案:onActivityResult is not calling after taking camera picture如果你不想声名鹊起。