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

画像ピッカーを使用する

ページを編集

このチュートリアルでは、Expo Image Picker を使って、Android、iOS、Web の React Native アプリでメディアライブラリから画像を選択し、表示する方法を学びます。


React Native は、<View>、<Text>、<Pressable> などの組み込みコンポーネントを標準的な構成要素として提供しています。ここで作成するのは、デバイスのメディアライブラリから画像を選択する機能です。これはコアコンポーネントだけでは実現できないため、この機能をアプリに追加するためにライブラリが必要になります。

Expo SDK のライブラリである expo-image-picker を使用します。

視聴:ユニバーサル Expo アプリで画像ピッカーを使用する
視聴:ユニバーサル Expo アプリで画像ピッカーを使用する

expo-image-picker を使ってデバイスのメディアライブラリから画像を選択する方法を学びます。


1

expo-image-picker をインストールする

expo-image-picker ライブラリをインストールするには、ターミナルで Ctrl + C を押して開発サーバーを停止してから、次のコマンドを実行します。

Terminal
- npx expo install expo-image-picker
- yarn expo install expo-image-picker
- pnpm expo install expo-image-picker
- bun expo install expo-image-picker

npx expo install コマンドは、ライブラリをインストールし、package.json のプロジェクトの依存関係に追加します。

2

デバイスのメディアライブラリから画像を選択する

expo-image-picker は、デバイスのメディアライブラリから画像や動画を選択するためのシステム UI を開く launchImageLibraryAsync() メソッドを提供します。このメソッドを呼び出す関数を作成し、前の章の primary ボタンに接続します。

src/app/(tabs)/index.tsx で expo-image-picker ライブラリをインポートし、Index コンポーネント内に pickImageAsync() 関数を作成します。

src/app/(tabs)/index.tsx
// ...rest of the import statements remain unchanged import * as ImagePicker from 'expo-image-picker'; export default function Index() { const pickImageAsync = async () => { const result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ['images'], allowsEditing: true, quality: 1, }); if (!result.canceled) { console.log(result); } else { alert('You did not select any image.'); } }; // ...rest of the code remains same }

上記のコードが何をしているのか確認しましょう。

  • launchImageLibraryAsync() メソッドは、さまざまなオプションを指定するためのオブジェクトを受け取ります。このオブジェクトは ImagePickerOptions オブジェクトで、メソッドを呼び出すときに渡します。
  • allowsEditing を true に設定すると、Android と iOS では選択時に画像をトリミングできます。Web では、トリミングの手順なしでブラウザのファイルピッカーが開きます。

3

ボタンを画像ピッカーに接続する

前の章の Button コンポーネントは、すでに onPress プロパティを受け取れます。src/app/(tabs)/index.tsx で、1 つ目の <Button> の onPress プロパティに pickImageAsync() 関数を渡します。

src/app/(tabs)/index.tsx
import { Platform, View, StyleSheet } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; import * as ImagePicker from 'expo-image-picker'; import Button from '@/components/button'; import ImageViewer from '@/components/image-viewer'; const PlaceholderImage = require('@/assets/images/background-image.png'); export default function Index() { const pickImageAsync = async () => { const result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ['images'], allowsEditing: true, quality: 1, }); if (!result.canceled) { console.log(result); } else { alert('You did not select any image.'); } }; return ( <SafeAreaView style={styles.container}> <View style={styles.imageContainer}> <ImageViewer imgSource={PlaceholderImage} /> </View> <View style={styles.footerContainer}> <Button theme="primary" label="Choose a photo" onPress={pickImageAsync} /> <Button label="Use this photo" onPress={() => alert('You pressed a button.')} /> </View> </SafeAreaView> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#25292e', alignItems: 'center', }, imageContainer: { flex: 1, paddingTop: Platform.select({ web: 96, default: 20 }), }, footerContainer: { flex: 1 / 3, alignItems: 'center', }, });

pickImageAsync() 関数は ImagePicker.launchImageLibraryAsync() を呼び出し、その結果を処理します。launchImageLibraryAsync() メソッドは、選択された画像に関する情報を含むオブジェクトを返します。

result オブジェクトとそのプロパティの例を次に示します。

{ "assets": [ { "assetId": null, "base64": null, "duration": null, "exif": null, "fileName": "ea574eaa-f332-44a7-85b7-99704c22b402.jpeg", "fileSize": 4513577, "height": 4570, "mimeType": "image/jpeg", "rotation": null, "type": "image", "uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252FStickerSmash-13f21121-fc9d-4ec6-bf89-bf7d6165eb69/ImagePicker/ea574eaa-f332-44a7-85b7-99704c22b402.jpeg", "width": 2854 } ], "canceled": false }

4

選択した画像を使用する

result オブジェクトには assets 配列があり、その中に選択された画像の uri が含まれています。この値を画像ピッカーから取得して、選択された画像をアプリに表示します。

src/app/(tabs)/index.tsx ファイルを変更します。

  1. React の useState フックを使って、selectedImage という状態変数を宣言します。この状態変数は選択された画像の URI を保持するために使います。
  2. pickImageAsync() 関数を更新して、画像の URI を selectedImage 状態変数に保存します。
  3. selectedImage をプロパティとして ImageViewer コンポーネントに渡します。
src/app/(tabs)/index.tsx
import { useState } from 'react'; import { Platform, View, StyleSheet } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; import * as ImagePicker from 'expo-image-picker'; import Button from '@/components/button'; import ImageViewer from '@/components/image-viewer'; const PlaceholderImage = require('@/assets/images/background-image.png'); export default function Index() { const [selectedImage, setSelectedImage] = useState<string | undefined>(undefined); const pickImageAsync = async () => { const result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ['images'], allowsEditing: true, quality: 1, }); if (!result.canceled) { setSelectedImage(result.assets[0].uri); } else { alert('You did not select any image.'); } }; return ( <SafeAreaView style={styles.container}> <View style={styles.imageContainer}> <ImageViewer imgSource={PlaceholderImage} selectedImage={selectedImage} /> </View> <View style={styles.footerContainer}> <Button theme="primary" label="Choose a photo" onPress={pickImageAsync} /> <Button label="Use this photo" onPress={() => alert('You pressed a button.')} /> </View> </SafeAreaView> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#25292e', alignItems: 'center', }, imageContainer: { flex: 1, paddingTop: Platform.select({ web: 96, default: 20 }), }, footerContainer: { flex: 1 / 3, alignItems: 'center', }, });

プレースホルダー画像の代わりに選択された画像を表示するために、selectedImage プロパティを ImageViewer コンポーネントに渡します。

  1. src/components/image-viewer.tsx ファイルを変更して、selectedImage プロパティを受け取れるようにします。
  2. 画像のソースが長くなっているので、imageSource という別の変数に切り出します。
  3. Image コンポーネントの source プロパティの値として imageSource を渡します。
src/components/image-viewer.tsx
import { StyleSheet } from 'react-native'; import { Image, type ImageSource } from 'expo-image'; type Props = { imgSource: ImageSource; selectedImage?: string; }; export default function ImageViewer({ imgSource, selectedImage }: Props) { const imageSource = selectedImage ? { uri: selectedImage } : imgSource; return <Image source={imageSource} style={styles.image} />; } const styles = StyleSheet.create({ image: { width: 320, height: 440, borderRadius: 18, }, });

上記のスニペットでは、Image コンポーネントは条件演算子を使って画像のソースを読み込みます。選択された画像は、プレースホルダー画像のようなローカルアセットではなく、uri 文字列 です。

アプリの状態を確認してみましょう。

まとめ

第 4 章:画像ピッカーを使用する

デバイスのメディアライブラリから画像を選択する機能の追加が完了しました。

次の章では、絵文字ピッカーのモーダルコンポーネントを作成する方法を学びます。

次へ:絵文字ピッカーのモーダルを作成する