序言
Andriod应用会涉及到要修改用户头像,用户需要选取一张图片,然后替换原有图片。系统提供了2中选取图片的方法:调用相机拍照、从手机图库中选取,下面针对下面两种做法介绍。
1、调用手机相机
流程:
- 调用系统相机
- 获取拍照图片,并进行旋转
- 对图片进行剪裁
- 剪裁的图片即可用图片
private void selectImageFromCamera() {
//第一步:在本地sd卡上创建一个图片文件,调用相机,把图片路径传给相机
File photo = new File(FileUtils.generateFileName(this, "png", "origin"));
cameraFilePath = Uri.fromFile(photo);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraFilePath);
startActivityForResult(intent, 1);
}
代码中的generateFileName是在sd卡上创建一个图片文件,并返回该文件的path
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
//第二步:相机获得照片,并且对照片进行压缩,然后根据原图对压缩图进行旋转处理
if (cameraFilePath != null) {
String filePath = cameraFilePath.getPath();
Bitmap bitmap = FileUtils.getThumbnailBitmap(filePath, 200);
String thumbnailPath = FileUtils.generateFileName(this, "png", "thum");
FileUtils.saveBitmap(bitmap, thumbnailPath);
new RotateTask().execute(filePath, thumbnailPath);
}
}
}
针对旋转 解释一下,相机拍照,可能是横着拿,拍出的照片也是横的,当手机放正之后,照片也需要对应旋转。接下来,看一下RotateTask的实现:
public class RotateTask extends AsyncTask<String, Void, String> {
@Override
protected void onPostExecute(String result) {
//第三步:旋转处理之后对缩略图进行剪裁处理
doCrop(result);
}
@Override
protected String doInBackground(String... params) {
int rotate = 0;
ExifInterface exif;
try {
exif = new ExifInterface(params[0]);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
rotate = 0;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_UNDEFINED:
rotate = 0;
break;
default:
rotate = 90;
}
} catch (IOException e) {
LogUtil.error(e,e.getMessage());
e.printStackTrace();
}
// It will rotate thumbnail image, not normal image
String path = FileUtils.rotateImage(rotate, params[1]);
FileUtils.deleteFile(params[0]);
return path;
}
}
旋转图片代码
public static String rotateImage(int degree, String imagePath) {
if (degree <= 0) {
return imagePath;
}
try {
Bitmap b = BitmapFactory.decodeFile(imagePath);
Matrix matrix = new Matrix();
if (b.getWidth() > b.getHeight()) {
matrix.setRotate(degree);
Bitmap newBitmap = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true);
b.recycle();
b = newBitmap;
}
String imageName = imagePath.substring(imagePath.lastIndexOf("/") + 1);
String imageType = imageName.substring(imageName.lastIndexOf(".") + 1);
FileOutputStream out = new FileOutputStream(imagePath);
if (imageType.equalsIgnoreCase("png")) {
b.compress(Bitmap.CompressFormat.PNG, 100, out);
} else if (imageType.equalsIgnoreCase("jpeg") || imageType.equalsIgnoreCase("jpg")) {
b.compress(Bitmap.CompressFormat.JPEG, 100, out);
}
out.flush();
out.close();
b.recycle();
} catch (Exception e) {
LogUtil.error(e, e.getMessage());
e.printStackTrace();
}
return imagePath;
}
旋转图后,对图片进行剪裁处理
private void doCrop(String path) {
Uri filePath = Uri.fromFile(new File(path));
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = this.getPackageManager().queryIntentActivities(intent, 0);
int size = list.size();
if (size != 0) {
try {
intent.setData(filePath);
intent.putExtra("crop", "true");
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName,
res.activityInfo.name));
startActivityForResult(i, 2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
剪裁之后,在OnActivityResult方法中加一段代码:
if (data != null && requestCode == 2) {
try {
Bitmap photo;
if(data.getExtras() != null){
photo = data.getExtras().getParcelable("data");
}else{
photo = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
}
ivPic.setImageBitmap(photo);
//todo 上传或缓存
}catch(IOException e){
e.printStackTrace();
}
}
2、从图库选取图片
流程:
- 打开图库
- 从图库中选取图片
- 剪裁图片
- 获取剪裁图片,即可使用图片
private void selectFromGallery() {
//注释的方式在android4.4中可能有问题,用下面的方式就没有问题了
// Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// intent.setType("image/*");
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
intent.putExtra("return-data", true);
Intent chooser = Intent.createChooser(intent,"选择图片来源");
startActivityForResult(chooser, 3);
}
接下来在onActivityResult中加一段代码:
if (requestCode == 3) {
doCrop(data);
}
之后代码与上面相同。