LoginSignup
1
0

cameraXで撮影した画像が勝手に回転するんだけど!?って貴方に【Androidアプリ開発】

Posted at
最終更新日: 20240304

いざカメラアプリの開発を開始すると
縦撮影した画像が勝手に90°回転するなど厄介な問題が発生します(端末によるかも)

最終的には下記の公式ドキュメントを見たらすんなり解決したんですけど
ここ以外に望んだ情報はなかった気がするので本記事に残しておきます

要件

画面の向きを縦に固定した状態で
画像を回転したい

ソース

Java言語で書いています
事情あってソースコードを全部載せることができないのですが
雰囲気でわかると思います

端末の回転情報を取得

最初は加速センサーで独自に回転情報取得していたけど
端末によって動作しないことが判明したので
OrientationEventListenerを採用しました

 
 OrientationEventListener orientationEventListener;
 private int deviceOrientation = 0;

 
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

         orientationEventListener = new OrientationEventListener(this) {
            @Override
            public void onOrientationChanged(int orientation) {
                if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
                    return;
                }
                if (orientation >= 45 && orientation < 135) {
                    deviceOrientation = Surface.ROTATION_270;
                } else if (orientation >= 135 && orientation < 225) {
                    deviceOrientation = Surface.ROTATION_180;
                } else if (orientation >= 225 && orientation < 315) {
                    deviceOrientation = Surface.ROTATION_90;
                } else {
                    deviceOrientation = Surface.ROTATION_0;
                }
            }
        };

imageCaptureに端末回転情報を渡す

本記事を見ているということは
imageCaptureを既に知ってると思うので端折ります

imageCapture.setTargetRotation(deviceOrientation);

ImageProxyから正しい回転に補正する値を取得

cameraXで撮影した画像データはImageProxy型変数に格納されます
本記事を見ている人は理解してると思うので端折ります

imageProxy.getImageInfo().getRotationDegrees();

Matrixで画像回転させる

今回の例だとImageProxyBitmapに変換してそれを回転させてますね

private Bitmap imageProxyToBitmap(ImageProxy image)
    {
        ImageProxy.PlaneProxy planeProxy = image.getPlanes()[0];
        ByteBuffer buffer = planeProxy.getBuffer();
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        Matrix matrix = new Matrix();
        matrix.postRotate(image.getImageInfo().getRotationDegrees());
        Bitmap bmp2 = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, false);
        return bmp2;
    }

まとめ

  1. OrientationEventListenerで端末の回転情報を取得
  2. imageCapture.setTargetRotationで撮影時の端末回転情報を設定
  3. imageProxy.getImageInfo().getRotationDegreesで画像撮影時の回転情報から正常な回転に補正する値を取得
  4. 補正値を使ってMatrixなどで画像を回転

おわりに

公式ドキュメント読むの大事だなーって今回の経験で体感した記憶があります

良かったらTwitterをフォローしてくれると泣いて喜びます

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0