今日因为学校里一个项目的开发,涉及到了Android 平台APP中的拍照功能的开发。参考了网上的一些代码,写了个比较简单的:
/**
* 调用相机拍照功能进行拍摄
*/
private View.OnClickListener btnClickHandler = new View.OnClickListener() {
Intent i;
File f;
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_dna_camera:
i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
f = new File(getMediaDir(), System.currentTimeMillis()+".jpg");
if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
currentPath = f.getAbsolutePath();
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(i, REQUEST_CODE_GET_PHOTO);
break;
}
}
};
/**
* 将照片显示在@ivpic
*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case REQUEST_CODE_GET_PHOTO:
if(resultCode==RESULT_OK){
ivpic.setImageURI(Uri.fromFile(new File(currentPath)));
}
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
但是在我的三星手机上出现了一个问题,就是拍的照片在APP中被读取出来后会旋转90°,这个问题也方便解决:
/**
* 获取图片的旋转角度
*/
public static int getBitmapDegree(String path) {
int degree = 0;
try {
// 从指定路径读取图片,并获取其EXIF信息
ExifInterface exifInterface = new ExifInterface(path);
// 获取图片旋转信息
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
/**
* 将图片按照指定角度进行旋转
*/
public static Bitmap rotateBitmapByDegree(Bitmap bitmap, int degree) {
// 根据旋转角度,生成旋转矩阵
Matrix matrix = new Matrix();
matrix.postRotate(degree);
// 将原始图片按照旋转矩阵进行旋转,并得到新图片
Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
if (bitmap != null && !bitmap.isRecycled()) {
bitmap.recycle();
}
return newBitmap;
}
然而这种方式会造成APP有些许卡顿,具体解决卡顿的方法仍在摸索。