在Ionic中将图像保存到图库时出错?

时间:2018-10-28 12:35:42

标签: cordova ionic-framework ionic3 base64

我正在使用File xmlFile = new File("example.xml"); JAXBContext jc = JAXBContext.newInstance(detail.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); detail d = (detail) unmarshaller.unmarshal(xmlFile); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(d, System.out); 插件将我的Base64 To Gallery图片存储到图库。

这是我的代码:

base64

我得到的错误是

  

无法解码图像。

我的要求是将生成的屏幕截图保存到我的画廊。我怎么做?任何帮助将非常感激。谢谢!

1 个答案:

答案 0 :(得分:1)

请尝试以下代码。这会将图像下载并保存到应用程序的文件夹中,并将显示在图库中。

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();
        })
    }