获取存储图片文件对象
public File getPhotoFile(Crime crime) {
//获取存放图片文件的路径
File extrenalFilesDir = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if(extrenalFilesDir == null) {
return null;
}
//如果存在路径,那么获取File对象,为crime.getPhotoFilename()对象
return new File(extrenalFilesDir, crime.getPhotoFilename());
}
启动相机
<span style="white-space:pre"> </span>mPhotoFile = getPhotoFile(crime);
<span style="white-space:pre"> </span>//打开相机的Intent
final Intent captureImage = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//当前存储的路径不为空并且存在能够接收当前intent的应用
boolean canTakePhoto = mPhotoFile != null && captureImage.resolveActivity(packageManager) != null;
if(canTakePhoto) {
//获取文件的Uri
Uri uri = Uri.fromFile(mPhotoFile);
//指定图片的储存位置
captureImage.putExtra(MediaStore.EXTRA_OUTPUT, uri);
}
mPhotoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(captureImage, REQUEST_PHOTO);
}
});
压缩图片同时将图片显示在设备上
mPhotoView = (ImageView) view.findViewById(R.id.crime_photo);
if(mPhotoView == null || !mPhotoFile.exists()) {
mPhotoView.setImageDrawable(null);
} else {
Bitmap bitmap = PictureUtils.getScaledBitmap(mPhotoFile.getPath(), getActivity());
mPhotoView.setImageBitmap(bitmap);
}
PictureUtiles.getScaledBitmap()方法
//获取屏幕尺寸
public static Bitmap getScaledBitmap(String path, Activity activity) {
Point size = new Point();
activity.getWindowManager().getDefaultDisplay().getSize(size);
return getScaledBitmap(path, size.x, size.y);
}
//destWidth destHeight对比的高宽
public static Bitmap getScaledBitmap(String path, int destWidth, int destHeight) {
//创建图片处理条件的对象
BitmapFactory.Options options = new BitmapFactory.Options();
//设置该属性为true,不加载图片到内存,只返回图片的宽高到options中。
options.inJustDecodeBounds = true;
//加载获取图片的宽高
BitmapFactory.decodeFile(path, options);
//当前图片高宽
float srcWidth = options.outWidth;
float srcHeight = options.outHeight;
int inSampleSize = 1;
if(srcHeight > destHeight || srcWidth > destWidth) {
if(srcWidth > srcHeight) {
inSampleSize = Math.round(srcHeight / destHeight);
} else {
inSampleSize = Math.round(srcWidth / destWidth);
}
}
//缩放比例
options = new BitmapFactory.Options();
options.inSampleSize = inSampleSize;
return BitmapFactory.decodeFile(path, options);
}