前回はexifInterfaceを使うためのgradleの設定をしたので、今回いよいよ実際にコードを書いて説明していきたいと思います。
前述のサポートにより、画像を扱うアプリではInputstreamを使うことでExifInterfaceがぐっと使いやすくなりました。
これにより、受け取ったURIから直接画像のexif情報を取得できるようになりました。
exifInterfaceをnewする前にInputStreamを初期化しておきましょう。
<pre>InputStream in = null;</pre>
ここでようやくexifInterfaceクラスを使うことが出来ます。次に向き(orientation)の取得ですが、ここではexifInterfaceクラスの
メソッドgetAttributeIntを使って向きを取得します。getAttributeIntの使い方ですが、取得する情報のタグを指定して値を取得する.
だけで使うことができます。例えば、何の変哲もない修正していない画像を取得する場合はExifInterface.ORIENTATION_NORMALを
指定します。
<pre>int orientation = exifInterface.getAttributeInt( ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);</pre>
無事に取得できれば後はこのorientationを変更したい角度に合わせてswitch文にセットすれば対象の画像のexif情報を
取ってくることができますね。
<pre>switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: rotation = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: rotation = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: rotation = 270; break; }</pre>
ExifInterface.ORIENTATION_ROTATE_〇〇はぱっと見分かりづらいですが、ものすごくかみ砕いて「この角度にすれば正しい位置になるよ」
と解釈しておけばその内慣れてくると思います。
次回はこのメソッドで取得したrotation変数を使って実際に向きを変えて表示してみましょう。
断片的なコードだけでは戸惑うかたもいると思うのでメソッド含めた全コードを載せておきます。
public class sample extends AppCompatActivity { private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sample); imageView = findViewById(R.id.image_view); int locatate; int rotation = 0; Bitmap bitmap; Uri uri; Intent intent = getIntent(); uri = intent.getParcelableExtra("imageUri"); try { bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri); //画像の向きを取得 getBmp(uri,rotation); } catch (IOException e) { e.printStackTrace(); } } public int getBmp(Uri uri,int rotation) { InputStream in = null; try { in = getContentResolver().openInputStream(uri); ExifInterface exifInterface = new ExifInterface(in); //緯度経度を取得 getLatlong(exifInterface); //画像の向きを取得 int orientation = exifInterface.getAttributeInt( ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: rotation = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: rotation = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: rotation = 270; break; } System.out.println(rotation); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException ignored) { } } } return rotation; } }