配置是少不了的:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="你的包名.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
res/xml/file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path path="Android/data/com.example.package.name/files/Pictures/OriPicture/" name="images" />
<external-path path="Android/data/com.example.package.name/files/Pictures/OriPicture/" name="images" />
<external-files-path path="files/Pictures/OriPicture" name="images"/>
<root-path path="" name="images"/>
<root-path path="" name="images"/>
<external-path name="external_files" path="."/>
</paths>
最好在代码里写入权限请求:
int cameraPermission = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA);
if (cameraPermission != PackageManager.PERMISSION_GRANTED) {
String[] PERMISSIONS_CAMERA_AND_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA};
ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS_CAMERA_AND_STORAGE, 0x001);
} else {
openCamera();
}
第一种开启方式:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,0x002);
第一种接收方式:
if (resultCode == RESULT_OK) {
if (requestCode == 0x002) {
Bundle bundle = data.getExtras();
Bitmap bitmap = (Bitmap) bundle.get("data");
iv.setImageBitmap(bitmap);
}
}
这种出来的图像是缩略图;
第二种开启方式:
private String PhotoPath;
PhotoPath = Environment.getExternalStorageDirectory() + "/Image_" + System.currentTimeMillis() + ".jpg";
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri photoUri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
photoUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", new File(PhotoPath));
} else {
photoUri = Uri.fromFile(new File(PhotoPath));
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(intent, 0x002);
第二种接收方式:
if (resultCode == RESULT_OK) {
if (requestCode == 0x002) {
try {
FileInputStream fis = new FileInputStream(PhotoPath);
Bitmap bitmap = BitmapFactory.decodeStream(fis);
iv.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
使用系统相机:
使用系统Intent:ACTION_IMAGE_CAPTURE
注册Camera功能: