我正在使用 Android Camera2 API 开发一个自定义相机应用程序,您可以在其中切换手机中可用的不同相机和视频分辨率。它还提供了拍摄平方 1:1 照片的可能性。为了拍摄方形照片,我拍摄了一张普通的 4:3 照片,然后对其进行裁剪以保持 1:1。(所以 4032x3024 将是 3024x3024)。
在某些分辨率下拍摄 1:1 图片时,我注意到一个问题,输出被略微裁剪(缩放)。这是用两种不同分辨率拍摄的同一张照片的结果:
我的 Nexus 5X 在 4:3 上支持 12MP、8MP、5MP 和 2MP。当我使用大于 5MP 的任何分辨率时会发生此问题。
我用来裁剪图像的方法如下:
ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
cropSquareImageByteArray(bytes);
cropSquareImageByteArray 方法:
public static byte[] cropSquareImageByteArray(byte[] bytes) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Bitmap dst = Bitmap.createBitmap(bitmap, 0, h - w, w, w);
dst.compress(Bitmap.CompressFormat.JPEG, 98, bos);
return bos.toByteArray();
}
我猜裁剪的原因是 16:9 容器中的 4:3 图像。因为我注意到打电话的时候
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
生成的位图输出的尺寸在 2MP 中为 1280x960 (4:3),在 5MP 中为 1600x1200 (4:3),但更大的分辨率为 1920x1080 (16:9),因此 4:3 图像调整为 16:9位图,可能会导致裁剪。
我试图弄清楚如何解决这个问题。我还检查了这篇文章Android 5.0 Wrong crop regions on preview surface 并捕获了静止图像,但在那里没有找到解决方案。
*编辑:我的 ImageReader 配置如下:
public void configureImageReader(Size pictureSizeValue, ImageReader.OnImageAvailableListener listener) {
if (mImageReader == null) {
mImageReader = ImageReader.newInstance(pictureSizeValue.getWidth(), pictureSizeValue.getHeight(),
ImageFormat.JPEG, 2);
}
mImageReader.setOnImageAvailableListener(listener, mBackgroundHandler);
}
的值pictureSizeValue
是我想要的输出。所以对于一个正方形的图像,它类似于 3024x3024。