我正在尝试使用以下代码调用Android摄像头:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
Uri uri = data.getData();
if (uri != null) Log.d("", uri.toString());
else Log.d("", "uri is null."); // ...but why? It should hold the image URI.
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
}
根据文件:
" MediaStore.EXTRA_OUTPUT - 此设置需要一个Uri对象,指定您要保存图片的路径和文件名。此设置是可选的,但强烈建议使用。如果未指定此值,则摄像头应用程序会将所请求的图片保存在默认位置,并使用在返回的意图的Intent.getData()字段中指定的默认名称。"
这不是我的经历。对我来说,此代码为data.getData()
返回null。我还尝试设置输出Uri,但这给了我一整套不同的问题......
还有其他人经历过这个吗?
答案 0 :(得分:1)
看一下这段代码
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
try {
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (f.exists()) {
Toast.makeText(this, "Image Found : "+f.getAbsolutePath().toString(), Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Image Not Found", Toast.LENGTH_SHORT).show();
}
}
}
你的意图应该是
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
答案 1 :(得分:1)
只要您的用户可以使用任何相机应用程序,您最好创建临时文件并将URI放到EXTRA_OUTPUT。规范不明确,并非每个应用程序都遵循它。 这是我用来保存文件的方法:
public static File reserveTempFile(String directory, String extension) throws IOException {
final File pathFile = new File(directory);
if (!pathFile.exists()) {
final boolean result = pathFile.mkdirs();
if (!result) {
throw new IOException("Can't create directory");
}
}
File file;
do {
String fileName = Long.toString(System.nanoTime());
if (Utils.isNotEmpty(extension)) {
fileName += "." + extension;
}
file = new File(pathFile, fileName);
} while (file.exists());
return file;
}