在使用camera2 API拍照后,生成的图片可能会由于旋转而出现不正确的方向。这通常是因为设备的方向不同于预期的方向所导致的。为了解决这个问题,可以按照以下步骤更改Google示例代码:
int rotation = getActivity().getWindowManager().getDefaultDisplay().getRotation(); mImageFile.mOrientation = ORIENTATIONS.get(rotation);
private static class ImageSaver implements Runnable { ... private final String mImageFile; private final int mOrientation;
public ImageSaver(Bitmap bitmap, String imageFile, int orientation) { .... mImageFile = imageFile; mOrientation = orientation; }
if(mOrientation != 0) { Matrix matrix = new Matrix(); matrix.postRotate(mOrientation);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); out = new FileOutputStream(mImageFile); rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); } else { out = new FileOutputStream(mImageFile); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); }