最終更新日: 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で画像回転させる
今回の例だとImageProxy
をBitmap
に変換してそれを回転させてますね
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;
}
まとめ
-
OrientationEventListener
で端末の回転情報を取得 -
imageCapture.setTargetRotation
で撮影時の端末回転情報を設定 -
imageProxy.getImageInfo().getRotationDegrees
で画像撮影時の回転情報から正常な回転に補正する値を取得 - 補正値を使って
Matrix
などで画像を回転
おわりに
公式ドキュメント読むの大事だなーって今回の経験で体感した記憶があります
良かったらTwitterをフォローしてくれると泣いて喜びます