清单声明
使用相机必须添加权限:(如果是使用系统相机应用可以不添加)
<uses-permission android:name="android.permission.CAMERA" />
同时必须声明使用特性,具体可以指定特定特性,该项是用在Google Play过滤不符要求的设备。可以设置required属性为必要或不必要
<uses-feature android:name="android.hardware.camera" android:required="false"/>
如果需要保存到sd卡
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
如果需要录像
<uses-permission android:name="android.permission.RECORD_AUDIO" />
如果需要使用GPS定位信息
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
...
<!-- Needed only if your app targets Android 5.0 (API level 21) or higher. -->
<uses-feature android:name="android.hardware.location.gps" />
需要记得调用hasSystemFeature(PackageManager.FEATURE_CAMERA)确保是否有相机。
打开系统相机应用
示例代码通过resolveActivity方法确保不会因为解析不到对应Activity而退出。
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
获取缩略图
系统相机应用把照片编码成Bitmap,放在了intent的extras中的”data”字段。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}
保存原始照片
要保存原始图片的话必须提供完整保存路径。恰当的路径是 getExternalStoragePublicDirectory(DIRECTORY_PICTURES)。该方法一般返回的路径是/mnt/sdcard/Pictures。如果想要私有化保存,可以调用Context. getExternalFilesDir()方法。该方法一般返回路径是/mnt/sdcard/Android/data/应用包名/files/Pictures。4.4(API 19)之前,读写该路径需要添加外存权限,4.4开始就不用了,因为该路径无法被其他应用读取,所以权限声明可以设置为如下(应用中只需要图片读取时)
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
...
</manifest>
注意,调用getExternalFilesDir()或者getFilesDir()返回的路径在卸载应用时会被删除。
保存的文件名需要设成不会互相冲突的
String mCurrentPhotoPath;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
我们就可以使用生成的文件路径打开系统相机应用
static final int REQUEST_TAKE_PHOTO = 1;
private void dispatchTakePictureIntent() {
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 {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
...
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
注意此处使用 getUriForFile(Context, String, File)来返回一个content://开头的URI,因为从7.0(API 24)开始,跨越包界限传递file://开头的URI会导致 FileUriExposedException,所以这里使用FileProvider
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
...
</application>
所以需要在清单文件中添加Provider,注意android:authorities字段必须与getUriForFile(Context, String, File)的第二个参数一致。在meta-data标签中,resource字段需要一个可用的路径,该路径是设置在一个专用的xml文件当中,如该例子所用的xml资源文件
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>
该路径对应 getExternalFilesDir(Environment.DIRECTORY_PICTURES)所返回的路径,注意要把示例包名替换为实际包名。有需要可以查看FileProvider的文档中除了external-path之外可用的路径。
把图片添加到系统图库
如果图片保存路径为getExternalFilesDir()的目录,因为该目录是应用私有的,会导致无法media scanner无法扫描到。以下的实例代码演示了如何把图片添加到图库中
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
解码缩放的图片
有限的内存中管理多张完整的图片是需要技巧的,详见示例代码
private void setPic() {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
mImageView.setImageBitmap(bitmap);
}