我已经为像我这样的问题找到了很多答案,但它们对我来说没有意义。让我解释一下。
我有一个ImageButton,让用户拍照并在界面上显示。当我尝试获取图像URI时,它返回null:
Uri uri = data.getData();
我已在互联网上进行了一些搜索,并找到了以下解决方案:
@Override
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
try {
if (resultCode == Activity.RESULT_OK) {
updateProfilePicure = Boolean.TRUE;
switch(requestCode){
case 0:
Bundle extras = data.getExtras();
Object xx = data.getData();
Bitmap imageBitmap = (Bitmap) extras.get("data");
Uri tempUri = getImageUri(imageBitmap);
imageView.setImageBitmap(imageBitmap);
break;
default: break;
}
}
} catch(Exception e){
e.printStackTrace();
}
}
public Uri getImageUri(Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(
ApplicationContext.getInstance().getContext().getContentResolver(), inImage,
"Title", null);
return Uri.parse(path);
}
对我而言,它没有意义,因为当调用方法 onActivityResult()时,图片已经保存在DCIM文件夹中,并且没有任何理由再次保存。那我为什么要用呢?
是否可以找到另一种从捕获的图像中检索URI的方法?
提前感谢。
答案 0 :(得分:5)
图片已保存在DCIM文件夹中,没有任何理由再次保存。
不一定。引用the documentation for ACTION_IMAGE_CAPTURE
:
调用者可以传递额外的EXTRA_OUTPUT来控制该图像的写入位置。如果EXTRA_OUTPUT不存在,则在额外字段中返回小尺寸图像作为Bitmap对象。
(这里的“额外字段”是一个额外的键入data
)
您粘贴的代码段正在检索data
个额外内容,因此图片不会存储在任何位置。
是否可以找到另一种从捕获的图像中检索URI的方法?
您已在第一个代码段中获得了此代码 - 如果您在Uri
请求中将EXTRA_OUTPUT
指定为ACTION_IMAGE_CAPTURE
,则会获得{{1返回Uri
传递给Intent
的图片。
答案 1 :(得分:2)
请看一下这个链接:http://developer.android.com/training/camera/photobasics.html
我在上一个项目中为图像工作了很多。用这样的东西拍照时:
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
图像未保存(至少它在我的项目中没有保存)。您可以使用以下代码直接获取缩略图:
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
如果你想拥有完整尺寸的图像,你应该保存它:
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 {
// This is where the file is created, create it as you wish. For more information about this, see the link or add a comment
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
...
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}