Loading Photos from the Filesystem
写真の撮影や、ファイルシステムへの保存は実装しました。しかし、最後に残っている機能があります。写真はファイルシステムに保存されていますが、各ファイルへのポインタを保存しておく必要があります。そうすれば、再び写真ギャラリーでその写真を表示することができます。
Capacitor の Preferences API を使えば、写真の配列をキーバリューストアに保存できます。
Preferences API
usePhotoGallery.ts を開き、まずストアのキーとして使う定数を定義します。
export const usePhotoGallery = (): {
addNewToGallery: () => Promise<void>;
photos: Ref<UserPhoto[]>;
} => {
const photos = ref<UserPhoto[]>([]);
// CHANGE: Add a key for photo storage
const PHOTO_STORAGE = 'photos';
// ...existing code...
};
次に、usePhotoGallery()メソッドの最後に、cachePhotosメソッドを呼び出して、photos配列を保存します。このようにして、新しい写真が撮られるたびに、photos配列が保存されます。そうすることで、ユーザーがアプリを閉じたり、別のアプリに切り替えたりしても、すべての写真データが保存されます。
import type { Photo } from '@capacitor/camera';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
import { Filesystem, Directory } from '@capacitor/filesystem';
// CHANGE: Add import
import { Preferences } from '@capacitor/preferences';
import type { Ref } from 'vue';
import { ref } from 'vue';
export const usePhotoGallery = (): {
addNewToGallery: () => Promise<void>;
photos: Ref<UserPhoto[]>;
} => {
// ...existing code...
// CHANGE: Add `cachePhotos()` method
const cachePhotos = () => {
Preferences.set({
key: PHOTO_STORAGE,
value: JSON.stringify(photos.value),
});
};
return {
addNewToGallery,
photos,
};
};
次に、Vue の watch メソッド で photos 配列を監視します。配列が変わるたびに(ここでは写真を撮影または削除したときに)cachePhotos メソッドを呼び出します。コードを再利用でき、ユーザーがいつアプリを閉じたり別のアプリに切り替えたりしても、写真のデータが保存されます。
usePhotoGallery() の return 文の前に watch() メソッドの呼び出しを追加します。
import type { Photo } from '@capacitor/camera';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { Preferences } from '@capacitor/preferences';
import type { Ref } from 'vue';
// CHANGE: Update import
import { ref, watch } from 'vue';
export const usePhotoGallery = (): {
addNewToGallery: () => Promise<void>;
photos: Ref<UserPhoto[]>;
} => {
// ...existing code...
// CHANGE: Add call to `watch` with `photos` array and `cachePhotos` method
watch(photos, cachePhotos);
return {
addNewToGallery,
photos,
};
};
写真データが保存されたら、usePhotoGallery()という関数の中に、loadSaved()という新しいメソッドを作成します。このメソッドを使って、保存されている写真データを取得できます。JSON 形式でphotos配列を取得する際には、同じキーを使用します。そして、その配列を実際の配列として解釈します。
export const usePhotoGallery = (): {
addNewToGallery: () => Promise<void>;
photos: Ref<UserPhoto[]>;
} => {
// ...existing code...
// CHANGE: Add `loadSaved()` method
const loadSaved = async () => {
const photoList = await Preferences.get({ key: PHOTO_STORAGE });
const photosInPreferences = photoList.value ? JSON.parse(photoList.value) : [];
};
watch(photos, cachePhotos);
return {
addNewToGallery,
photos,
};
};
モバイル(次のセクションで扱います)では、画像タグのソース <img src="x" /> に Filesystem 上の各写真ファイルを直接指定すれば表示できます。Web では、Photo オブジェクトに新しく追加する base64 プロパティを使い、Filesystem から各画像を base64 形式で読み込む必要があります。これは Filesystem API が内部で IndexedDB を使用するためです。次のコードを追加して loadSaved() メソッドを完成させます。
export const usePhotoGallery = (): {
addNewToGallery: () => Promise<void>;
photos: Ref<UserPhoto[]>;
} => {
// ...existing code...
// CHANGE: Update `loadSaved()` method
const loadSaved = async () => {
const photoList = await Preferences.get({ key: PHOTO_STORAGE });
const photosInPreferences = photoList.value ? JSON.parse(photoList.value) : [];
// CHANGE: Display the photo by reading into base64 format
for (const photo of photosInPreferences) {
const file = await Filesystem.readFile({
path: photo.filepath,
directory: Directory.Data,
});
photo.webviewPath = `data:image/jpeg;base64,${file.data}`;
}
photos.value = photosInPreferences;
};
watch(photos, cachePhotos);
return {
addNewToGallery,
photos,
};
};
ここまでで usePhotoGallery.ts は次のようになります。
import type { Photo } from '@capacitor/camera';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { Preferences } from '@capacitor/preferences';
import type { Ref } from 'vue';
import { ref, watch } from 'vue';
export const usePhotoGallery = (): {
addNewToGallery: () => Promise<void>;
photos: Ref<UserPhoto[]>;
} => {
const photos = ref<UserPhoto[]>([]);
const PHOTO_STORAGE = 'photos';
const addNewToGallery = async () => {
// Take a photo
const capturedPhoto = await Camera.getPhoto({
resultType: CameraResultType.Uri, // file-based data; provides best performance
source: CameraSource.Camera, // automatically take a new photo with the camera
quality: 100, // highest quality (0 to 100)
});
const fileName = Date.now() + '.jpeg';
const savedImageFile = await savePicture(capturedPhoto, fileName);
photos.value = [savedImageFile, ...photos.value];
};
const savePicture = async (photo: Photo, fileName: string): Promise<UserPhoto> => {
const base64Data = await base64FromPath(photo.webPath!);
const savedFile = await Filesystem.writeFile({
path: fileName,
data: base64Data,
directory: Directory.Data,
});
// Use webPath to display the new image instead of base64 since it's
// already loaded into memory
return {
filepath: fileName,
webviewPath: photo.webPath,
};
};
const base64FromPath = async (path: string): Promise<string> => {
const response = await fetch(path);
const blob = await response.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = reject;
reader.onload = () => {
if (typeof reader.result === 'string') {
resolve(reader.result);
} else {
reject('method did not return a string');
}
};
reader.readAsDataURL(blob);
});
};
const cachePhotos = () => {
Preferences.set({
key: PHOTO_STORAGE,
value: JSON.stringify(photos.value),
});
};
const loadSaved = async () => {
const photoList = await Preferences.get({ key: PHOTO_STORAGE });
const photosInPreferences = photoList.value ? JSON.parse(photoList.value) : [];
for (const photo of photosInPreferences) {
const file = await Filesystem.readFile({
path: photo.filepath,
directory: Directory.Data,
});
photo.webviewPath = `data:image/jpeg;base64,${file.data}`;
}
photos.value = photosInPreferences;
};
watch(photos, cachePhotos);
return {
addNewToGallery,
photos,
};
};
export interface UserPhoto {
filepath: string;
webviewPath?: string;
}
usePhotoGallery() が保存済みの画像を読み込めるようになりました。この処理を使うようにファイルを更新しましょう。onMounted lifecycle method の中で loadSaved を呼び出すと、ユーザーが初めて Photo Gallery を開いたときにすべての写真が読み込まれ、画面に表示されます。
usePhotoGallery.tsのコードを以下のように更新してください。
import type { Photo } from '@capacitor/camera';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { Preferences } from '@capacitor/preferences';
import type { Ref } from 'vue';
// CHANGE: Update import
import { ref, onMounted, watch } from 'vue';
export const usePhotoGallery = (): {
addNewToGallery: () => Promise<void>;
photos: Ref<UserPhoto[]>;
} => {
const photos = ref<UserPhoto[]>([]);
const PHOTO_STORAGE = 'photos';
const addNewToGallery = async () => {
// Take a photo
const capturedPhoto = await Camera.getPhoto({
resultType: CameraResultType.Uri, // file-based data; provides best performance
source: CameraSource.Camera, // automatically take a new photo with the camera
quality: 100, // highest quality (0 to 100)
});
const fileName = Date.now() + '.jpeg';
const savedImageFile = await savePicture(capturedPhoto, fileName);
photos.value = [savedImageFile, ...photos.value];
};
const savePicture = async (photo: Photo, fileName: string): Promise<UserPhoto> => {
const base64Data = await base64FromPath(photo.webPath!);
const savedFile = await Filesystem.writeFile({
path: fileName,
data: base64Data,
directory: Directory.Data,
});
// Use webPath to display the new image instead of base64 since it's
// already loaded into memory
return {
filepath: fileName,
webviewPath: photo.webPath,
};
};
const base64FromPath = async (path: string): Promise<string> => {
const response = await fetch(path);
const blob = await response.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = reject;
reader.onload = () => {
if (typeof reader.result === 'string') {
resolve(reader.result);
} else {
reject('method did not return a string');
}
};
reader.readAsDataURL(blob);
});
};
const cachePhotos = () => {
Preferences.set({
key: PHOTO_STORAGE,
value: JSON.stringify(photos.value),
});
};
const loadSaved = async () => {
const photoList = await Preferences.get({ key: PHOTO_STORAGE });
const photosInPreferences = photoList.value ? JSON.parse(photoList.value) : [];
for (const photo of photosInPreferences) {
const file = await Filesystem.readFile({
path: photo.filepath,
directory: Directory.Data,
});
photo.webviewPath = `data:image/jpeg;base64,${file.data}`;
}
photos.value = photosInPreferences;
};
// CHANGE: Add call to `onMounted()` with the `loadSaved()` method
onMounted(loadSaved);
watch(photos, cachePhotos);
return {
addNewToGallery,
photos,
};
};
export interface UserPhoto {
filepath: string;
webviewPath?: string;
}
これらの手順に従った後、画像リンクが壊れていたり写真が欠けている場合は、ブラウザの開発者ツールを開き、localStorageとIndexedDBの両方をクリアする必要があるかもしれません。
localStorage ではドメイン http://localhost:8100 とキー CapacitorStorage.photos を探します。IndexedDB では「FileStorage」というストアを探します。写真には /DATA/123456789012.jpeg のようなキーが設定されています。
これで完了です!Web で動作する完全な Photo Gallery 機能を Ionic アプリに構築できました。次は、iOS と Android 向けのモバイルアプリに変換します。