Ionic – Capacitor : load and save image

With Ionic and the capacitor extension « Filesystem » we can load an image from the Internet, save it locally and then use the local file.

Importants information :

  1.  We could use the base64 string directly bu if you display multiple times the same image it’s slow, using the url is better.
  2. On the web, we can’t save locally and use the image, we directly use the url from the Internet.
  3. When you re-install the apps from Xcode, the local file is deleted, consequently we have to test the file exist.
export class MyObject {
    id: number;
    imageUrl: string = null;            // Url on the Internet
    imageBase64: string = null;         // Base64 string representation (can be used in <img src>)
    imageLocalFileName: string = null;  // Image local filename
    imageLocalUrl: string = null;       // Image local URL (use in <img src>)


    setImage(http: HttpClient, imageUrl) {
        //If the image URL is different from the current image or if base64 == null
        if(imageUrl != this.imageUrl || this.imageBase64 == null
            //Only on Ios/Android, if the local file does not exist (after re-install for example)
            || (Capacitor.getPlatform() != 'web' && (this.imageLocalFileName == null 
                || Capacitor.convertFileSrc(await Filesystem.getUri({ path: this.imageLocalFileName, directory: Directory.Data})['uri']) === undefined))) {
            
            var config = { responseType: 'blob' as 'blob' };
            //Load the file from the Internet
            http.get(imageUrl, config).subscribe(
                data => {
                    //Convert image to base64
                    blobToBase64(data).then(async function(res) {
                        this.imageBase64 = res;
                        this.imageUrl = imageUrl;

                        if (Capacitor.getPlatform() === 'web') {
                            //On web we use the URL because we can't save locally the image and use then use it
                            this.imageLocalUrl = this.imageLocalUrl;
                        } else {
                            //On Ios:Android we save the file

                            //Create a new filename
                            var fileName: string = 'image_' + this.id + '.svg';
                            while(Capacitor.convertFileSrc(await Filesystem.getUri({ path: fileName, directory: Directory.Data})['uri']) !== undefined) {
                                fileName = 'image_' + this.id + '_' + Math.random() * 1000 + '.svg';
                            }
                            
                            //Save the file
                            const savedFile = await Filesystem.writeFile({
                                path: fileName,
                                data: this.imageBase64,
                                directory: Directory.Data
                            });

                            this.imageLocalFileName = fileName;
                            this.imageLocalUrl = Capacitor.convertFileSrc(savedFile['uri']);
                        }
                    }.bind(this));
                },
                error => {
                });
        }
    }
}

Now display the image like this :

<img [src]="sanitizer.bypassSecurityTrustUrl(obj.imageLocalUrl)">

Categories:

Tags:

No responses yet

Laisser un commentaire