Android系统相机在使用前置摄像头拍照的时候,最终会将拍下的画面做镜像翻转,来达到真实的视角效果,但由于Android手机大多将前置摄像头摆在左右两边(iPhone在靠中间的位置,效果会好很多),导致翻转后与拍照预览的画面还是会有较大的差别,所以我们这里就再做一次镜像将图片翻转回去。
图片镜像
public Bitmap convertBmp(Bitmap bmp) {
int w = bmp.getWidth();
int h = bmp.getHeight();
Matrix matrix = new Matrix();
matrix.postScale(-1, 1); // 镜像水平翻转
Bitmap convertBmp = Bitmap.createBitmap(bmp, 0, 0, w, h, matrix, true);
return convertBmp;
}图片的翻转主要用到变换矩阵中的缩放操作,x轴都乘-1,y轴保持不变。
图片保存
private void saveBitmap() {
try {
File outFile = new File(Utils.getRootPath(),
System.currentTimeMillis() + ".jpg");
outFile.createNewFile();
FileOutputStream outStream = new FileOutputStream(outFile);
mBitmap.compress(CompressFormat.JPEG, 100, outStream);
outStream.close();
} catch (IOException e) {
}
}上面的方法会将一个bitmap保存为jpg的图片文件。
拍照或者从本地选取图片
这里我们直接使用Intent来调用相机应用拍照或者图片应用来选择图片,如下
private void dispatchTakePictureIntent(int actionCode) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
File picFile = new File(Utils.getCameraFilePath(), System.currentTimeMillis() + ".jpg");
picFile.createNewFile();
mPhotoPath = picFile.getPath();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(picFile));
} catch (IOException e) {
e.printStackTrace();
}
startActivityForResult(intent, actionCode);
}
private void dispatchGetPictureIntent(int actionCode) {
mPhotoPath = null;
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
"image/*");
startActivityForResult(intent, actionCode);
}在调用其它应用后我们需要得到操作的图片,所以使用startActivityForResult()方法,在onActivityResult()中得到图片路径,
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
// mPhotopath为空是指从相册选择的图片
if (mPhotoPath == null) {
Uri photoUri = data.getData();
ContentResolver cr = this.getContentResolver();
Cursor cursor = cr.query(photoUri, null, null, null, null);// 根据Uri从数据库中找
if (cursor.moveToFirst()) {
// 获取图片路径
mPhotoPath = cursor.getString(cursor
.getColumnIndex("_data"));
}
cursor.close();
}
if (mBitmap != null) {
mBitmap.recycle();
mBitmap = null;
}
mBitmap = BitmapFactory.decodeFile(mPhotoPath);
if (mBitmap != null) {
Bitmap temp = convertBmp(mBitmap);
if (temp != null) {
mImageView.setImageBitmap(temp);
mBitmap.recycle();
mBitmap = temp;
}
}
mImageView.setImageBitmap(mBitmap);
}因为从相册选取本地图片后intent中只会保留一个缩略图,因此我们需要去查询媒体库来得到图片的具体路径。
下面是实际的运行效果
本文介绍了Android系统相机在使用前置摄像头拍照时会进行镜像翻转,以达到真实视角效果,但因手机设计原因,仍存在差异。文章讨论了如何再次进行镜像操作,以修正这一问题,并通过Intent调用相机或图片应用进行演示。
301

被折叠的 条评论
为什么被折叠?



