將照片儲存到檔案系統
我們現在可以拍攝多張照片,並將它們顯示在應用程式第二個索引標籤上的照片庫中。但是,這些照片目前不會永久儲存,因此當應用程式關閉時,它們將會被刪除。
檔案系統 API
幸運的是,將它們儲存到檔案系統只需幾個步驟。首先,在 PhotoService
類別 (src/app/services/photo.service.ts
) 中建立一個新的類別方法 savePicture()
。我們傳入 photo
物件,它代表新捕獲的裝置照片
private async savePicture(photo: Photo) { }
我們可以立即在 addNewToGallery()
中使用這個新方法
public async addNewToGallery() {
// 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)
});
// Save the picture and add it to photo collection
const savedImageFile = await this.savePicture(capturedPhoto);
this.photos.unshift(savedImageFile);
}
我們將使用 Capacitor 檔案系統 API 將照片儲存到檔案系統。首先,將照片轉換為 base64 格式,然後將資料饋送到檔案系統的 writeFile
函數。正如您所回憶的,我們透過在 tab2.page.html
中將每個圖片的來源路徑(src
屬性)設定為 webviewPath 屬性,來在螢幕上顯示每張照片。因此,請設定它然後返回新的 Photo 物件。
private async savePicture(photo: Photo) {
// Convert photo to base64 format, required by Filesystem API to save
const base64Data = await this.readAsBase64(photo);
// Write the file to the data directory
const fileName = Date.now() + '.jpeg';
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
};
}
readAsBase64()
是我們接下來將定義的輔助函數。透過單獨的方法組織它很有用,因為它需要少量平台特定(網頁與行動裝置)邏輯 - 稍後會詳細說明。現在,實作在網頁上執行的邏輯
private async readAsBase64(photo: Photo) {
// Fetch the photo, read as a blob, then convert to base64 format
const response = await fetch(photo.webPath!);
const blob = await response.blob();
return await this.convertBlobToBase64(blob) as string;
}
private convertBlobToBase64 = (blob: Blob) => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = reject;
reader.onload = () => {
resolve(reader.result);
};
reader.readAsDataURL(blob);
});
在網頁上以 base64 格式取得相機照片似乎比在行動裝置上稍微棘手。實際上,我們只是使用內建的網頁 API:fetch() 作為一種將檔案讀取為 blob 格式的巧妙方法,然後使用 FileReader 的 readAsDataURL() 將照片 blob 轉換為 base64。
完成!每次拍攝新照片時,現在都會自動儲存到檔案系統。