拍照

注意:本页介绍的是已废弃的 Camera 类。建议您改用 CameraX;在特定的使用场景下,也可以改用 Camera2。CameraX 和 Camera2 都支持 Android 5.0(API 级别 21)及更高版本。

本课程向您介绍了如何通过委托设备上的其他相机应用来拍摄照片(如果您要构建自己的相机功能,请参阅控制相机)。

假设您要实现一项众包气象服务,将由运行您客户端应用的设备拍摄的天空照片融合到一起,制作出一张全球气象图。集成照片只是您应用功能的一小部分。您希望以最省事的方式拍照,而不是重新构建相机。值得高兴的是,大多数搭载 Android 的设备已经至少安装了一个相机应用。在本课程中,您将学习如何使用相机应用拍照。

请求相机功能

如果您的应用的基本功能是拍照,请将其在 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 相机应用会对 return Intent 中的照片进行编码,将其作为键 "data" 下 extra 中的小型 Bitmap 传递给 onActivityResult()。下面的代码会检索此图片,并将其显示在一个 ImageView 中。

KotlinJava
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)
   
}
}
@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 相机应用会保存完整尺寸的照片,前提是您为相应照片指定了用于保存的文件夹。您必须为相机应用应保存照片的位置提供一个完全限定的文件名称。

通常情况下,用户使用设备相机拍摄的所有照片都应保存在设备的公共外部存储设备中,以供所有应用访问。合适的共享照片目录由具有 DIRECTORY_PICTURES 实参的 getExternalStoragePublicDirectory() 提供。此方法提供的目录会在所有应用之间共享。在 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 内调用了此方法)。

KotlinJava
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
   
}
}
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,如下所示:

KotlinJava
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)
           
}
       
}
   
}
}
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);
       
}
   
}
}

注意:我们使用的是 getUriForFile(Context, String, File),它会返回 content:// URI。对于以 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>

确保授权字符串与 getUriForFile(Context, String, File) 的第二个实参匹配。在提供程序定义的元数据部分,您可以看到提供程序需要在专用资源文件 res/xml/file_paths.xml 中配置符合条件的路径。下面显示了此特定示例所需的内容:

<?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>

路径组件对应于调用 Environment.DIRECTORY_PICTURESgetExternalFilesDir() 返回的路径。请务必将 com.example.package.name 替换为应用的实际软件包名称。此外,请参阅 FileProvider 的文档,查看除 external-path 之外您还可以使用的其他路径说明符的详细说明。

将照片添加到图库

通过 intent 制作照片时,您应该知道图片所在的位置,因为您一开始就指定了保存相应图片的位置。对于所有其他人而言,为了让您的照片可供访问,最简单的方式可能是让其可从系统的媒体提供商访问。

注意:如果您将照片保存到 getExternalFilesDir() 提供的目录中,则媒体扫描器将无法访问相应的文件,因为这些文件不公开,仅供您的应用访问。

下面的示例方法演示了如何调用系统的媒体扫描器,以将您的照片添加到媒体提供商的数据库中,使 Android 图库应用中显示这些照片,并使它们可供其他应用使用。

KotlinJava
private fun galleryAddPic() {
   
Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE).also { mediaScanIntent ->
       
val f = File(currentPhotoPath)
        mediaScanIntent
.data = Uri.fromFile(f)
        sendBroadcast
(mediaScanIntent)
   
}
}
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 扩展到内存数组(该内存数组已调整为与目标视图的大小匹配),从而大幅减少动态堆的使用量。下面的示例方法演示了这种方法。

KotlinJava
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)
   
}
}
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);
}