This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.

Expo 媒体库(旧版) iconExpo 媒体库(旧版)

提供对设备媒体库的访问的库。

Android
iOS
tvOS
Included in Expo Go
Recommended version:
~58.0.7

expo-media-library 提供对用户媒体库的访问权限,允许他们从你的应用中访问现有的图片和视频,并保存新的媒体内容。你还可以订阅用户媒体库的任何更新。

安装

🌐 Installation

Terminal
- npx expo install expo-media-library
- yarn expo install expo-media-library
- pnpm expo install expo-media-library
- bun expo install expo-media-library

If you are installing this in an existing React Native app, make sure to install expo in your project.

应用配置中的配置

🌐 Configuration in app config

如果你在项目中使用配置插件(连续原生生成 (CNG)),可以使用其内置的 配置插件 来配置 expo-media-library。该插件允许你配置无法在运行时设置并且需要构建新的应用二进制文件才能生效的各种属性。如果你的应用不使用 CNG,则需要手动配置该库。

🌐 You can configure expo-media-library using its built-in config plugin if you use config plugins in your project (Continuous Native Generation (CNG)). The plugin allows you to configure various properties that cannot be set at runtime and require building a new app binary to take effect. If your app does not use CNG, then you'll need to manually configure the library.

Example app.json with config plugin

{ "expo": { "plugins": [ [ "expo-media-library", { "photosPermission": "Allow $(PRODUCT_NAME) to access your photos.", "savePhotosPermission": "Allow $(PRODUCT_NAME) to save photos.", "isAccessMediaLocationEnabled": true, "granularPermissions": ["audio", "photo"] } ] ] } }

Configurable properties

NameDefaultDescription
photosPermission"Allow $(PRODUCT_NAME) to access your photos."
Only for: 
iOS

Sets the iOS NSPhotoLibraryUsageDescription permission message in Info.plist.

savePhotosPermission"Allow $(PRODUCT_NAME) to save photos."
Only for: 
iOS

Sets the iOS NSPhotoLibraryAddUsageDescription permission message in Info.plist.

preventAutomaticLimitedAccessAlertfalse
Only for: 
iOS

Prevents the automatic limited access alert from being shown when the user has limited access to the photo library. Useful for apps that want to access only the limited photo library without having iOS forcibly show the alert.

isAccessMediaLocationEnabledfalse
Only for: 
Android

Sets whether or not to request the ACCESS_MEDIA_LOCATION permission on Android.

granularPermissions["photo", "video", "audio"]
Only for: 
Android

Sets which GranularPermission values to include, determining which media permissions (READ_MEDIA_IMAGES, READ_MEDIA_VIDEO, READ_MEDIA_AUDIO) will be added to the Android manifest. Matches the behavior of the runtime API.

Are you using this library in an existing React Native app?

如果你没有使用连续原生生成(CNG),或者你是手动使用原生 android 和 ios 项目,那么你需要在你的原生项目中添加以下权限和配置:

🌐 If you're not using Continuous Native Generation (CNG) or you're using native android and ios projects manually, then you need to add following permissions and configuration to your native projects:

安卓

  • 要访问资源位置(纬度和经度 EXIF 标签),请在项目的 android/app/src/main/AndroidManifest.xml 中添加 ACCESS_MEDIA_LOCATION 权限:

    <uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION" />
  • Scoped storage 从 Android 10 开始可用。要使 expo-media-library 能与 Scoped Storage 一起使用,你需要将以下配置添加到你的 android/app/src/main/AndroidManifest.xml 中:

    <manifest ... > <application android:requestLegacyExternalStorage="true" ...> </manifest>

iOS

  • 将 NSPhotoLibraryUsageDescription 和 NSPhotoLibraryAddUsageDescription 键添加到你项目的 ios/[app]/Info.plist 文件中:

    <key>NSPhotoLibraryUsageDescription</key> <string>Give $(PRODUCT_NAME) permission to access your photos</string> <key>NSPhotoLibraryAddUsageDescription</key> <string>Give $(PRODUCT_NAME) permission to save photos</string>

用法

🌐 Usage

Fetching albums and displaying assets
import { useState, useEffect } from 'react'; import { Button, Text, ScrollView, StyleSheet, Image, View, Platform } from 'react-native'; import * as MediaLibrary from 'expo-media-library/legacy'; export default function App() { const [albums, setAlbums] = useState(null); const [permissionResponse, requestPermission] = MediaLibrary.usePermissions(); async function getAlbums() { if (permissionResponse.status !== 'granted') { await requestPermission(); } const fetchedAlbums = await MediaLibrary.getAlbumsAsync({ includeSmartAlbums: true, }); setAlbums(fetchedAlbums); } return ( <View style={styles.container}> <Button onPress={getAlbums} title="获取专辑" /> <ScrollView> {albums && albums.map((album) => <AlbumEntry album={album} />)} </ScrollView> </View> ); } function AlbumEntry({ album }) { const [assets, setAssets] = useState([]); useEffect(() => { async function getAlbumAssets() { const albumAssets = await MediaLibrary.getAssetsAsync({ album }); setAssets(albumAssets.assets); } getAlbumAssets(); }, [album]); return ( <View key={album.id} style={styles.albumContainer}> <Text> {album.title} - {album.assetCount ?? 'no'} assets </Text> <View style={styles.albumAssetsContainer}> {assets && assets.map((asset) => ( <Image source={{ uri: asset.uri }} width={50} height={50} /> ))} </View> </View> ); } %%placeholder-start%%const styles = StyleSheet.create({ ... }); %%placeholder-end%%const styles = StyleSheet.create({ container: { flex: 1, gap: 8, justifyContent: 'center', }, albumContainer: { paddingHorizontal: 20, marginBottom: 12, gap: 4, }, albumAssetsContainer: { flexDirection: 'row', flexWrap: 'wrap', }, });

已知的限制

🌐 Known limitations

清空相册

🌐 Empty albums

由于 Android 系统的限制,不可能创建空相册。必须传入一个现有的资源以添加到相册,或传入本地资源的 URI,这将用于在相册中创建一个新的资源。

🌐 Due to system limitations on Android, it is impossible to create empty albums. It is necessary to either pass an existing asset to add to the album or a URI of a local resource, which will be used to create a new asset inside the album.

在相册之间移动资源

🌐 Moving assets between albums

Android 11 引入了权限更改,使在相册之间移动资源的操作每次都需要用户确认。因此,在创建新资源时,建议在调用 createAssetAsync 方法时传入 album 参数,而不是先创建资源再将其移动到相册,这样可以自动将资源添加到相册,而无需用户确认。

🌐 Android 11 introduced permission changes that make the operation of moving assets between albums require confirmation from the user every time. Therefore, when creating a new asset, instead of creating the asset and then moving it to the album, it is recommended to pass the album parameter to the createAssetAsync method, which will automatically add the asset to the album without the need for user confirmation.

图片方向错误

🌐 Wrong orientation of images

在 Android 上,如果使用 getAssetsAsync 而不使用 resolveWithFullInfo: true,图片方向可能会不正确,因为只有在启用该选项时才会读取包含方向信息的 EXIF 数据。

🌐 On Android, when using getAssetsAsync without resolveWithFullInfo: true, image orientation may be incorrect because EXIF data (which includes orientation) is only read when that option is enabled.

resolveWithFullInfo 的性能影响

🌐 Performance impact of resolveWithFullInfo

在 Android 上,在 getAssetsAsync 中启用 resolveWithFullInfo: true 会显著增加请求时间(约 5 倍),因为库会为每张图片获取 EXIF 和位置信息。该库只会为图片资源解析位置信息和 EXIF 数据。iOS 会在批量结果中为所有资源类型包含 GPS 位置,而这个选项在 iOS 上没有效果。

🌐 On Android, enabling resolveWithFullInfo: true in getAssetsAsync significantly increases request time (~5×), because the library fetches EXIF and location data per image. The library resolves location and EXIF data for image assets only. iOS includes GPS location for all asset types in batch results, and this option does nothing.

应用接口

🌐 API

import * as MediaLibrary from 'expo-media-library/legacy';

No API data file found, sorry!

权限

🌐 Permissions

安卓

🌐 Android

通过此库的 AndroidManifest.xml 会自动添加以下权限:

🌐 The following permissions are added automatically through this library's AndroidManifest.xml:

Android permissionDescription

READ_EXTERNAL_STORAGE

Allows an application to read from external storage.

WRITE_EXTERNAL_STORAGE

Allows an application to write to external storage.

READ_MEDIA_IMAGES

Allows an application to read image files from external storage.

READ_MEDIA_VIDEO

Allows an application to read video files from external storage.

READ_MEDIA_AUDIO

Allows an application to read audio files from external storage.

READ_MEDIA_VISUAL_USER_SELECTED

Allows an application to read image or video files from external storage that a user has selected via the permission prompt photo picker.

iOS

该库使用以下用法描述键:

🌐 The following usage description keys are used by this library:

Info.plist keyDescription

NSPhotoLibraryUsageDescription

A message that tells the user why the app is requesting access to the user’s photo library.

NSPhotoLibraryAddUsageDescription

A message that tells the user why the app is requesting add-only access to the user’s photo library.