出于某种原因,我的相机应用程序保存了所有旋转 90 度的照片(只有在横向模式下使用相机拍摄的照片才看起来正确)我相信 onPictureTaken 应该自动旋转照片但我读到三星设备有问题(我没有去过能够在另一个品牌上进行测试,所以我不知道是不是这样)。这是我的代码:
public void onPictureTaken(byte[] data, Camera camera) {
// Generate file name
FileOutputStream outStream = null;
outStream = new FileOutputStream(filePath);
outStream.write(data);
outStream.close();
我原以为可以通过检查方向和旋转字节数组来解决这个问题,但必须有一种更直接的方法来做到这一点,因为处理字节数组很痛苦。 如何确保照片的保存方向与拍摄方向一致?
尝试这样的事情:
int orientation = Exif.getOrientation(data);
Log.d("#", "onPictureTaken().orientation = " + orientation);
if(orientation != 0) {
Bitmap bmpSrc = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap bmpRotated = CameraUtil.rotate(bmpSrc, orientation);
bmpSrc.recycle();
try {
FileOutputStream localFileOutputStream = new FileOutputStream(filePath);
bmpRotated.compress(Bitmap.CompressFormat.JPEG, 90,localFileOutputStream);
localFileOutputStream.flush();
localFileOutputStream.close();
bmpRotated.recycle();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
} else {
try {
FileOutputStream localFileOutputStream = new FileOutputStream(filePath);
localFileOutputStream.write(data);
localFileOutputStream.flush();
localFileOutputStream.close();
} catch (IOException localIOException)
{
Log.e("#",localIOException.getMessage());
}
}
有不同的方式来获取你的图像,作为数据,作为流,作为文件,对于相机和画廊以及其他应用程序来说也是不同的。对于它们中的每一个,您都有另一种方法来访问方向标签。确定方向后,您可以旋转图像。
你——或者就此而言,每个人——真的应该得到一个 Nexus,他们很好,可以为你旋转图像并将方向设置为 0,而像三星这样懒惰的人只是存储图像并设置方向标签。 ;)
Android graphics framework
,以下内容可能对您有用:
public void onPictureTaken(byte[] data, Camera camera) {
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
ExifInterface exif = new ExifInterface(filePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.postRotate(180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.postRotate(270);
break;
default:
break;
}
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
FileOutputStream outStream = new FileOutputStream(filePath);
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Bitmap
对象作为解码和操作图像数据的简单方法。Matrix
,因为旋转是由矩阵乘法表示的线性变换,因为我们不需要直接操作像素值。Exif
元数据来确定我们需要如何旋转图像以使其正确定向。Bitmap
和原始的Matrix
创建一个新的Bitmap
。FileOutputStream
将图像写入预定义的类成员filePath
.