注意:本页面参考的是已弃用的 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 相机应用会将照片编码为返回到 onActivityResult()
的 Intent
,作为 extras 中的一个小型 Bitmap
,键为 "data"
。以下代码会检索此图像并将其显示在 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); } } }
注意:我们正在使用 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>
确保 authorities 字符串与 getUriForFile(Context, String, File)
的第二个参数匹配。在提供程序定义的元数据部分,您可以看到提供程序希望在专用资源文件中配置合格的路径,
<?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>
路径组件对应于调用 getExternalFilesDir()
并传入 Environment.DIRECTORY_PICTURES
时返回的路径。请务必将 com.example.package.name
替换为您的应用的实际包名。另外,请查阅 FileProvider
的文档,以获取除了 external-path
之外还可以使用的路径说明符的详细说明。
将照片添加到图库
当您通过 intent 创建照片时,您应该知道图像的存储位置,因为您一开始就指定了保存位置。对于其他人来说,让您的照片可访问的最简单方法可能是使其可从系统的媒体提供程序 (Media Provider) 访问。
注意:如果您将照片保存到 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); }