rchau
rchau

Reputation: 535

Error saving image to the gallery in Ionic?

I am using Base64 To Gallery plugin to store my base64 image to gallery.

This is my code:

 savePhoto() {
    this.screen.URI(100).then(
      res => {
        this.base64ToGallery.base64ToGallery(res.URI, { prefix: '_bilar', mediaScanner: true }).then(
          res => {
            alert('Saved image to gallery ' + res);
            this.base64value = res.URI;
          },
          err => alert('Error saving image to gallery ' + err)
        );
      }
    )
  }

The error which I am getting is

The image could not be decoded.

My requirement is save the generated screenshot to my gallery. How do I do that? Any help would be much appreciated. Thank You!

Upvotes: 0

Views: 2242

Answers (1)

Arj 1411
Arj 1411

Reputation: 1401

Try this below code. This will download and save the image to the app's folder and will present on the gallery.

downloadImage(fileName, ext, base64) {
        let storageDirectory: string = "";
        //Select Storage Location
        if (this.platform.is('ios')) {
            storageDirectory = cordova.file.documentsDirectory + '<Your Folder Name>/';
        }
        else if (this.platform.is('android')) {
            storageDirectory = cordova.file.externalDataDirectory + '<Your folder name>/';
        }
        else {
            return false;
        }
        //Request Access
        if (this.platform.is("android")) {
            this.diagnostic.requestRuntimePermission('READ_EXTERNAL_STORAGE').then(() => {
                console.log("Success");
            })
        }
        //Download Image
        var uri = encodeURI('data:' + "image/png" + ';base64,' + base64);
        var fileURL = storageDirectory + "Image.png".replace(/ /g, '%20');
        this.fileTransfer.download(uri, fileURL).then((success) => {
            base64 = 'data:' + "image/png" + ';base64,' + base64;
            const alertSuccess = this.alertCtrl.create({
                title: `Download Succeeded!`,
                subTitle: `Image was successfully downloaded`,
                buttons: ['Ok']
            });
            alertSuccess.present();
        }, error => {
            const alertFailure = this.alertCtrl.create({
                title: `Download Failed!`,
                subTitle: `Image was not successfully downloaded. Error code: ${error.code}`,
                buttons: ['Ok']
            });
            alertFailure.present();
        })
    }

Upvotes: 1

Related Questions