我在android中实现自定义相机。我使用默认显示方向的其中一部手机是横向模式。拍照时图像的预览效果很好。尽管如此,当旋转并保存图像时,图像会变形。
这是我用来旋转图像的代码:
Display display = ((WindowManager) MyCamera.this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();
if (rotation == Surface.ROTATION_0) {
rotation = 90;
} else if (rotation == Surface.ROTATION_90) {
rotation = 180;
} else if (rotation == Surface.ROTATION_180) {
rotation = 270;
} else if (rotation == Surface.ROTATION_270) {
rotation = 360;
}
DisplayMetrics metrics = getResources().getDisplayMetrics();
Options options = new BitmapFactory.Options();
options.inDither = false;
options.inScaled = false;
options.inDensity=metrics.densityDpi;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bm = BitmapFactory.decodeByteArray(imgBytes, 0, imgBytes.length, options);
Matrix m = new Matrix();
m.postRotate(rotation);
Bitmap nbm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), m, true);
file = MyCamera.this.saveBitmap(nbm);
这是我用来保存位图图像的代码:
private File saveBitmap(Bitmap image) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null) {
Log.d(TAG,"Error creating media file, check storage permissions: ");// e.getMessage());
return null;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
finish();
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
finish();
}
return pictureFile;
}
以下是一些示例,说明图像在相机预览模式下的外观以及它在手机外部存储设备上保存后的效果。