以前、「【React Native】アルバムやカメラから画像を取得できるライブラリ「react-native-image-picker」」という記事で紹介した「react-native-image-picker」ライブラリですが、最近になって別のアプリに導入したら、メソッドが変わっていたので備忘録としてまとめ。
自分の記事を参考にして実装したらエラーが発生したので少々焦りました…。
GitHub のページはこちらから。
GitHub – react-native-image-picker/react-native-image-picker: A React Native module that allows you to use native UI to select media from the device library or directly from the camera.
https://github.com/react-native-image-picker/react-native-image-picker
インストール手順は割愛します!
大きな変更点としては、showImagePicker API が削除された点です。
その代わり、カメラから撮影したり、アルバムから写真選択する場合は、下記のように launchCamera と launchImageLibrary メソッドを定義してそれぞれ呼び出します。
import { launchCamera, launchImageLibrary } from 'react-native-image-picker';
個人的に、ImagePicker.showImagePicker() メソッドがとても使いやすかったので…削除されてしまって残念です。
具体的な使用方法は下記のとおりです。
まず、オプションの値を設定します。
const options = {
mediaType: 'photo',
maxWidth: 1000,
maxHeight: 1000,
quality: 0.8,
saveToPhotos: true,
};
で、カメラで撮影する場合とアルバムから写真を選択する場合の処理をそれぞれ下記のように関数内に定義します。
// カメラで撮影する
this.takePhoto = () => {
launchCamera(options, (response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
const source = { uri: response.uri };
this.setState({
image: source,
});
}
});
}
// アルバムから選択する
this.choosePhoto = () => {
launchImageLibrary(options, (response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
const source = { uri: response.uri };
this.setState({
image: source,
});
}
});
}
処理としては以上です!
以前のアプリはライブラリのバージョンを更新していないため、現時点ではそのままでも大丈夫ではありますが…近いうちにコードを確認しなければいけませんね。
以上、React Native のライブラリ「react-native-image-picker」の変更点まとめでした。
ライブラリの変更は気をつけないといけませんね…。
ご参考になれば幸いです。