繁体   English   中英

Android相机在纵向模式下保存图片

[英]Android Camera Saving Pictures in Portrait Mode

我正在尝试在我的应用程序中使用相机,我希望能够在横向和纵向模式下使用它。 我在横向模式下创建图片没有任何困难,但我还没有找到一种在纵向模式下保存图片的好方法。

当我想在纵向模式下制作图片时,我需要先将displayorientation设置为portrait,如下所示:

switch (windowManager.getDefaultDisplay().getRotation()) {
    case android.view.Surface.ROTATION_0:
        mCamera.setDisplayOrientation(90);
        break;
    case android.view.Surface.ROTATION_90:
        mCamera.setDisplayOrientation(0);
        break;
    case android.view.Surface.ROTATION_180:
        mCamera.setDisplayOrientation(270);
        break;
    case android.view.Surface.ROTATION_270:
        mCamera.setDisplayOrientation(180);
        break;
}

但随后图片仍以横向模式保存。 我找到的一个解决方案是更改相机的旋转参数,如下所示:

public void onOrientationChanged(int orientation) {
    if (orientation == ORIENTATION_UNKNOWN) return;
    android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
    android.hardware.Camera.getCameraInfo(cameraId, info);
    orientation = (orientation + 45) / 90 * 90;
    int rotation = 0;
    if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
        rotation = (info.orientation - orientation + 360) % 360;
    } else {  // back-facing camera
        rotation = (info.orientation + orientation) % 360;
    }
    mParameters.setRotation(rotation);
}

这种方法的问题在于它可能只是在EXIF标题中设置方向而不是实际旋转图片(我正在使用的设备就是这种情况)。

另一种方法是在拍摄照片后旋转实际数据,如下所示:

Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length);
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix mtx = new Matrix();
mtx.postRotate(rotate);
bitmap=  Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
currentData = stream.toByteArray();

但是这种方法需要10秒钟(这太长了)虽然我可以将这些代码放在AsyncTask中,但是我需要一到几秒钟的数据,所以我还是需要等待。

到目前为止,我还没有找到更好的解决方案。

我找到了一个解决方案,让我仍然需要等待一两秒钟,但这对我来说足够快。 这是一个非常简单的修复,只需使用Matrix.postRotate方法,但更改:

bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);

至:

bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

对我来说这是一个非常好的解决方案,特别是因为在其他任何地方我已经使用过.jpg图像,所以无论如何将Bitmap压缩到.png都没有多大意义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM