ios android 保存图片到相册

1,171 阅读1分钟

最近做项目,有个需求是base64图片下载保存到本地并分享给微信好友或朋友圈的功能呢;大致实现代码如下

Android

安卓使用的插件是cordova-plugin-file
1、安装命令如下:

cordova plugin add cordova-plugn-file

2、config.xml配置代码如下:

<preference name="AndroidPersistentFileLocation" value="Compatibility" />

3、创建并文件文件夹

createAndWriteFile(data){
    //持久化数据保存
    let self = this;
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fs => {
        console.log('打开的文件系统: ' + JSON.stringify(fs));
        fs.root.getDirectory('Photos', { create: true, exclusive: false }, function (dirEntry){
            //文件内容
            const dataObj = self.dataURLtoBlob(data.data);
            //写入文件
            // this.writeFile(fileEntry, dataObj);
            self.saveFile(dirEntry, dataObj, data.fileName);


        }, err => {
            console.log('文件夹创建失败');
        });
    }, err => {
        console.log('文件系统加载失败');
    });
}

4、保存图片文件

saveFile(dirEntry, fileData, fileName) {
    console.log('dirEntry:' + JSON.stringify(dirEntry));
    dirEntry.getFile(fileName, { create: true, exclusive: false }, fileEntry => {
        this.writeFile(fileEntry, fileData);
    }, err => {
        console.log('文件创建失败');
    });
},

5、base64转blob

dataURLtoBlob(dataurl) {
    let arr = dataurl.split(',');
    //注意base64的最后面中括号和引号是不转译的   
    let _arr = arr[1].substring(0,arr[1].length-2);
    let mime = arr[0].match(/:(.*?);/)[1],
        bstr =atob(_arr),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {
        type: mime
    });
}

6、文件内容写入文件

writeFile(fileEntry, dataObj) {
    //创建一个写入对象
    fileEntry.createWriter(fileWriter => {

        //文件写入成功
        fileWriter.onwriteend = () => {
            console.log("Successful file read...");
            console.log(dataObj.type);
            if (dataObj.type == "image/jpeg" || dataObj.type == 'image/jpg') {
                this.readBinaryFile(fileEntry);
            }
            else {
                this.readFile(fileEntry);
            }
        };

        //文件写入失败
        fileWriter.onerror = function (e) {
            console.log("Failed file read: " + e.toString());
        };
        //写入文件
        fileWriter.write(dataObj);
    });
}

7、读取文件

readFile(fileEntry) {
    console.log('读取文件');
    fileEntry.file(function (file) {
        var reader = new FileReader();
        reader.onloadend = function() {
            // alert(this.result);
            console.log('文件读取成功');
        };
        reader.readAsText(file);
    }, err => {
        console.log('文件读取失败');
    });
}

8、读取图片文件

readBinaryFile(fileEntry) {
    console.log('读取图片文件:'+ JSON.stringify(fileEntry));
    let self = this;
    fileEntry.file(function (file) {
        var reader = new FileReader();

        reader.onloadend = function() {
            //加载成功显示图片
            // var blob = new Blob([new Uint8Array(this.result)], { type: "image/jpeg" });
            console.log(file);
            self.imgSrc = file.localURL;
            Toast.success('下载成功');
            window.frames[0].postMessage({
                fileType: 'image',
                filePath: file.localURL,
                fileId: self.msg.fileId,
            }, 'http://jschen.natapp1.cc');
            // self.msg = null; 
        };
        reader.readAsArrayBuffer(file);
    }, err => {
        console.log('文件读取失败');
    });
}

IOS

1、ios用的插件Canvas2ImagePlugin,安装命令如下:

cordova plugin add https://github.com/devgeeks/Canvas2ImagePlugin.git

2、权限配置
需要在plist文件里配置权限 Privacy-Photo Library Addition

3、保存方法

cordova.exec(
    res => {
        Toast.success('下载成功');
    }, err => {
        Toast.fail(JSON.stringify(err));
    }, 
    'Canvas2ImagePlugin', 
    'saveImageDataToLibrary', 
    [base64.replace(/data:image\/jpg;base64,/, '')]
);