@capacitor/camera
相机 API 提供了使用相机拍摄照片或从照片库中选择现有照片的功能。
npm install @capacitor/camera
npx cap sync
iOS
iOS 要求您在
Info.plist
中为您的应用程序添加以下使用描述并填写。
NSCameraUsageDescription
(
隐私 - 相机使用描述
)
NSPhotoLibraryAddUsageDescription
(
隐私 - 照片库添加使用描述
)
NSPhotoLibraryUsageDescription
(
隐私 - 照片库使用描述
)
阅读有关
配置
Info.plist
的内容,在
iOS 指南
中了解有关在 Xcode 中设置 iOS 权限的更多信息。
Android
从设备图库中选择现有图像时,现在将使用 Android 照片选择器组件。照片选择器适用于满足以下条件的设备
运行 Android 11 或 12 并支持 Google Play 服务的旧设备和 Android Go 设备可以安装照片选择器的移植版本。要通过 Google Play 服务启用照片选择器模块的自动安装移植版本,请在
AndroidManifest.xml
文件中将以下条目添加到
<application>
标签中
<service android:name="com.google.android.gms.metadata.ModuleDependencies"
android:enabled="false"
android:exported="false"
tools:ignore="MissingClass">
<intent-filter>
<action android:name="com.google.android.gms.metadata.MODULE_DEPENDENCIES" />
</intent-filter>
<meta-data android:name="photopicker_activity:0:required" android:value="" />
</service>
如果未添加该条目,则不支持照片选择器的设备将使用
Intent.ACTION_OPEN_DOCUMENT
作为照片选择器组件的回退选项。
相机插件不需要任何权限,除非使用
saveToGallery: true
,在这种情况下,应将以下权限添加到您的
AndroidManifest.xml
中
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
您也可以仅为将请求权限的 Android 版本指定这些权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29"/>
存储权限用于读取/保存照片文件。
阅读有关 设置权限 的内容,在 Android 指南 中了解有关设置 Android 权限的更多信息。
此外,由于相机 API 会启动一个单独的 Activity 来处理拍照,因此您应在
App
插件中监听
appRestoredResult
以处理在 Activity 运行期间操作系统终止应用程序的情况下发送的任何相机数据。
此插件将使用以下项目变量(在您应用程序的
variables.gradle
文件中定义)
androidxExifInterfaceVersion
:
androidx.exifinterface:exifinterface
的版本(默认:
1.3.6
)
androidxMaterialVersion
:
com.google.android.material:material
的版本(默认:
1.10.0
)
PWA 说明
PWA 元素 是相机插件正常工作的必要条件。
import { Camera, CameraResultType } from '@capacitor/camera';
const takePicture = async () => {
const image = await Camera.getPhoto({
quality: 90,
allowEditing: true,
resultType: CameraResultType.Uri
});
// image.webPath will contain a path that can be set as an image src.
// You can access the original file using image.path, which can be
// passed to the Filesystem API to read the raw data of the image,
// if desired (or pass resultType: CameraResultType.Base64 to getPhoto)
var imageUrl = image.webPath;
// Can be set to the src of an image now
imageElement.src = imageUrl;
};
API
getPhoto(...)
pickImages(...)
pickLimitedLibraryPhotos()
getLimitedLibraryPhotos()
checkPermissions()
requestPermissions(...)