注: このページでは、サポートが終了した Camera クラスについて言及していますが、CameraX(特定のユースケースでは Camera2)の使用をおすすめします。CameraX と Camera2 は、どちらも Android 5.0(API レベル 21)以降に対応しています。
このレッスンでは、デバイス上の別のカメラアプリに処理を委任することによって写真を撮影する方法について説明します(独自のカメラ機能を作成する場合は、カメラを制御するをご覧ください)。
たとえば、クライアント アプリが実行されているデバイスで撮影した空の写真を組み合わせることによってグローバルな天気情報マップを作成する、クラウド ソーシングによる天気情報サービスを実装するとします。写真を統合する処理はアプリのごく一部にすぎません。写真の撮影は最小限の操作で行えるようにし、カメラを作り変えずに済むようにします。幸い、ほとんどの Android デバイスには少なくとも 1 つのカメラアプリがあらかじめインストールされています。このレッスンでは、写真を撮影する方法について説明します。
カメラ機能をリクエストする
写真の撮影機能がアプリに不可欠な場合、Google Play でのアプリの表示をカメラが搭載されているデバイスに制限します。アプリにカメラが必要なことを示すには、マニフェスト ファイルに <uses-feature>
タグを追加します。
<manifest ... > <uses-feature android:name="android.hardware.camera" android:required="true" /> ... </manifest>
アプリでカメラを使用するものの、アプリが動作するうえでカメラが必要ない場合は、android:required
を false
に設定します。そうすることで、カメラを搭載していないデバイスでも Google Play でアプリをダウンロードできるようになります。次に、hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)
を呼び出して、実行時にカメラを使用できるかどうかを確認する必要があります。カメラを使用できない場合は、カメラ機能を無効にする必要があります。
サムネイルを取得する
写真を撮影するというシンプルな機能がアプリの最終目的でない場合、カメラアプリから画像を取得し直してなんらかの処理を行いたいと思うかもしれません。
Android カメラアプリは、キー "data"
で、extras の小さな Bitmap
として onActivityResult()
に提供されるリターン Intent
で写真をエンコードします。次のコードでは、その画像を取得して ImageView
に表示しています。
Kotlin
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { val imageBitmap = data.extras.get("data") as Bitmap imageView.setImageBitmap(imageBitmap) } }
Java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); imageView.setImageBitmap(imageBitmap); } }
注: "data"
を使用して取得したサムネイル画像は、アイコンには適しているかもしれませんが、それ以上のものではないでしょう。フルサイズの画像を扱うにはもう少し手間がかかります。
フルサイズの写真を保存する
Android カメラアプリは、保存先のファイルを指定すると、フルサイズの写真を保存します。カメラアプリで写真を保存する場合、完全修飾ファイル名を指定する必要があります。
通常、ユーザーがデバイスのカメラで撮影した写真は、すべてのアプリからアクセスできるよう、デバイスのパブリック外部ストレージに保存する必要があります。共有対象の写真に適したディレクトリは、getExternalStoragePublicDirectory()
で指定されます(DIRECTORY_PICTURES
引数を使用)。このメソッドで指定されたディレクトリはすべてのアプリで共有されます。Android 9(API レベル 28)以前では、このディレクトリの読み取りと書き込みに、それぞれ READ_EXTERNAL_STORAGE
権限と WRITE_EXTERNAL_STORAGE
権限が必要となります。
<manifest ...> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ... </manifest>
Android 10(API レベル 29)以降では、写真の共有に適したディレクトリは MediaStore.Images
テーブルです。当該アプリで撮影した写真にアクセスする必要があるだけならば、ストレージの権限を宣言する必要はありません。
ただし、引き続き写真を自分のアプリに限定公開する場合は、Context.getExternalFilesDir()
で指定されたディレクトリを代わりに使用できます。Android 4.3 以前では、このディレクトリへの書き込みには WRITE_EXTERNAL_STORAGE
権限も必要になります。Android 4.4 以降では、他のアプリからこのディレクトリにアクセスできないため、この権限は不要になりました。そのため、maxSdkVersion
属性を追加することにより、以前のバージョンの Android でのみ権限をリクエストする必要があることを宣言できます。
<manifest ...> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" /> ... </manifest>
注: getExternalFilesDir()
または getFilesDir()
で指定されたディレクトリに保存したファイルは、ユーザーがアプリをアンインストールすると削除されます。
ファイルを保存するディレクトリを決めたら、ファイル名を衝突しないように付ける必要があります。後で使用する場合に備えて、パスをメンバー変数に保存することもできます。以下に、日時スタンプを使用して新しい写真の一意のファイル名を返すメソッドの例を示します(この例では、Context
内からメソッドを呼び出すことを前提としています)。
Kotlin
lateinit var currentPhotoPath: String @Throws(IOException::class) private fun createImageFile(): File { // Create an image file name val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date()) val storageDir: File = getExternalFilesDir(Environment.DIRECTORY_PICTURES) return File.createTempFile( "JPEG_${timeStamp}_", /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ).apply { // Save a file: path for use with ACTION_VIEW intents currentPhotoPath = absolutePath } }
Java
String currentPhotoPath; private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES); File image = File.createTempFile( imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ); // Save a file: path for use with ACTION_VIEW intents currentPhotoPath = image.getAbsolutePath(); return image; }
写真用のファイルの作成に使用可能なこのメソッドを使って、次のように Intent
を作成して呼び出せるようになりました。
Kotlin
private fun dispatchTakePictureIntent() { Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent -> // Ensure that there's a camera activity to handle the intent takePictureIntent.resolveActivity(packageManager)?.also { // Create the File where the photo should go val photoFile: File? = try { createImageFile() } catch (ex: IOException) { // Error occurred while creating the File ... null } // Continue only if the File was successfully created photoFile?.also { val photoURI: Uri = FileProvider.getUriForFile( this, "com.example.android.fileprovider", it ) takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI) startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE) } } } }
Java
private void dispatchTakePictureIntent() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Ensure that there's a camera activity to handle the intent if (takePictureIntent.resolveActivity(getPackageManager()) != null) { // Create the File where the photo should go File photoFile = null; try { photoFile = createImageFile(); } catch (IOException ex) { // Error occurred while creating the File ... } // Continue only if the File was successfully created if (photoFile != null) { Uri photoURI = FileProvider.getUriForFile(this, "com.example.android.fileprovider", photoFile); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } } }
注: ここでは、content://
URI を返す getUriForFile(Context, String, File)
を使用しています。Android 7.0(API レベル 24)以降を対象とする最近のアプリでは、パッケージの境界を越えて file://
URI を渡すと FileUriExposedException
が発生します。そこで、FileProvider
を使用して画像を保存するというより一般的な方法をご紹介します。
次に、FileProvider
を設定する必要があります。アプリのマニフェストでプロバイダをアプリに追加します。
<application> ... <provider android:name="androidx.core.content.FileProvider" android:authorities="com.example.android.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data> </provider> ... </application>
authorities の文字列が getUriForFile(Context, String, File)
の 2 番目の引数と一致していることを確認してください。プロバイダは有効なパスが専用のリソース ファイル(
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-files-path name="my_images" path="Pictures" /> </paths>
path コンポーネントは、Environment.DIRECTORY_PICTURES
を指定して getExternalFilesDir()
を呼び出したときに返されるパスと一致します。com.example.package.name
はアプリの実際のパッケージ名で置き換えてください。また、FileProvider
のドキュメントで、external-path
以外に使用可能なパス指定子の詳細を確認してください。
写真をギャラリーに追加する
インテントを介して写真を作成する場合、画像の保存場所を最初に自分で指定するため、画像の場所を覚えておく必要があります。自分以外の全員が写真にアクセスできるようにする場合、システムのメディア プロバイダからアクセスできるようにする方法がおそらく最も簡単でしょう。
注: getExternalFilesDir()
で指定されたディレクトリに写真を保存した場合、ファイルは自分のアプリに限定公開されるため、メディア スキャナはファイルにアクセスできません。
次の例のメソッドは、システムのメディア スキャナを呼び出して写真をメディア プロバイダのデータベースに追加し、Android ギャラリー アプリやその他のアプリで写真を使用できるようにする方法を示しています。
Kotlin
private fun galleryAddPic() { Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE).also { mediaScanIntent -> val f = File(currentPhotoPath) mediaScanIntent.data = Uri.fromFile(f) sendBroadcast(mediaScanIntent) } }
Java
private void galleryAddPic() { Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); File f = new File(currentPhotoPath); Uri contentUri = Uri.fromFile(f); mediaScanIntent.setData(contentUri); this.sendBroadcast(mediaScanIntent); }
サイズ変更された画像をデコードする
メモリが不足していると、多数のフルサイズ画像を管理することが難しくなる場合があります。画像をいくつか表示しただけでアプリでメモリ不足が生じる場合は、表示先のビューのサイズに合わせてすでにサイズ変更された JPEG をメモリ配列に展開することにより、使用する動的ヒープの量を大幅に減らすことができます。次のメソッドの例はこの手法を示しています。
Kotlin
private fun setPic() { // Get the dimensions of the View val targetW: Int = imageView.width val targetH: Int = imageView.height val bmOptions = BitmapFactory.Options().apply { // Get the dimensions of the bitmap inJustDecodeBounds = true BitmapFactory.decodeFile(currentPhotoPath, bmOptions) val photoW: Int = outWidth val photoH: Int = outHeight // Determine how much to scale down the image val scaleFactor: Int = Math.max(1, Math.min(photoW / targetW, photoH / targetH)) // Decode the image file into a Bitmap sized to fill the View inJustDecodeBounds = false inSampleSize = scaleFactor inPurgeable = true } BitmapFactory.decodeFile(currentPhotoPath, bmOptions)?.also { bitmap -> imageView.setImageBitmap(bitmap) } }
Java
private void setPic() { // Get the dimensions of the View int targetW = imageView.getWidth(); int targetH = imageView.getHeight(); // Get the dimensions of the bitmap BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(currentPhotoPath, bmOptions); int photoW = bmOptions.outWidth; int photoH = bmOptions.outHeight; // Determine how much to scale down the image int scaleFactor = Math.max(1, Math.min(photoW/targetW, photoH/targetH)); // Decode the image file into a Bitmap sized to fill the View bmOptions.inJustDecodeBounds = false; bmOptions.inSampleSize = scaleFactor; bmOptions.inPurgeable = true; Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath, bmOptions); imageView.setImageBitmap(bitmap); }