重点是uniapp图片转base64,web端作为知识扩充进行了实现。对方法进行了promise封装。 uniapp方法封装抛出了错误。web端未抛出。只参考网络例子进行了测试.

uniapp

  • 以下方法兼容app端, 即iosAndroid.
        // 支持以下图片路径: 相对路径 - 相对于当前页面的host位置,如"a.jpg",注意当前页面为网络地址则不支持; 绝对路径 - 系统绝对路径,如Android平台"/storage/sdcard0/Android/data/io.dcloud.HBuilder/.HBuilder/apps/HBuilder/www/a.jpg",iOS平台"/var/mobile/Containers/Data/Application/757966CF-345C-4348-B07F-EEF83CF9A369/Library/Pandora/apps/HBuilder/www/a.png"; 相对路径URL(RelativeURL) - 以"_"开头的相对路径,如"_www/a.jpg"、"_doc/b.jpg"、"_documents/c.jpg"、"_downloads/d.jpg"; 本地路径URL - 以“file://”开头,后面跟随系统绝对路径。

        // 平台支持
        // Android - 2.2+ (支持) :
        // 支持jpg/jpeg、png等格式图片。

        // iOS - 5.0+ (支持) :
        // 支持jpg/jpeg、png、tif/tiff、gif、bmp、ico、cur、xbm等格式图片。
        getAppImageBase64(src) {
            return new Promise((resolve, reject) => {
                let base64Data = null;
                plus.zip.compressImage(
                    {
                        src: plus.io.convertLocalFileSystemURL(src),
                        dst: `_doc/temp/${+new Date()}.jpg`,
                        quality: 70
                    },
                    ({ target, size }) => {
                        console.log(target, size);
                        plus.io.resolveLocalFileSystemURL(target, file => {
                            const fileReader = new plus.io.FileReader();
                            fileReader.readAsDataURL(file);
                            fileReader.onloadend = ({ target: { result } }) => {
                                base64Data = result.replace(/^data:image\/\w+;base64,/, '');
                                resolve(base64Data);
                            };
                            fileReader.onerror = err => {
                                console.log('读取文件失败', err);
                            };
                        });
                    },
                    e => {
                        reject(e);
                    }
                );
            });
        }

web端

方法一

        getWebImageBase64_1(imgUrl) {
            return new Promise((resolve, reject) => {
                window.URL = window.URL || window.webkitURL;
                let xhr = new XMLHttpRequest();
                xhr.open('get', imgUrl, true);
                // 至关重要
                xhr.responseType = 'blob';
                xhr.onload = function() {
                    if (this.status == 200) {
                        //得到一个blob对象
                        let blob = this.response;
                        console.log('blob', blob);
                        // 至关重要
                        let oFileReader = new FileReader();
                        oFileReader.onloadend = function(e) {
                            let base64 = e.target.result;
                            // console.log('方式一》》》》》》》》》', base64);
                            resolve(base64)
                        };
                        oFileReader.readAsDataURL(blob);
                    }
                };
                xhr.send();
            })
            
        }

方法二

        getWebImageBase64_2() {
            let img = 'https://img.cdn.aliyun.dcloud.net.cn/uni-app/doc/uni-app-frame-0310.png'; //imgurl 就是你的图片路径
            function getBase64Image(img) {
                let canvas = document.createElement('canvas');
                canvas.width = img.width;
                canvas.height = img.height;
                let ctx = canvas.getContext('2d');
                ctx.drawImage(img, 0, 0, img.width, img.height);
                let ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase();
                let dataURL = canvas.toDataURL('image/' + ext);
                return dataURL;
            }

            return new Promise((resolve, reject) => {
                let image = new Image();
                image.src = img;
                image.setAttribute("crossOrigin",'Anonymous')
                image.onload = function() {
                    let base64 = getBase64Image(image);
                    // console.log(base64);
                    resolve(base64)
                }
            })
        }
    }

uniapp测试页面源码

<template>
    <view class="content">
        <image class="logo" src="/static/logo.png"></image>
        <view class="text-area">
            <text class="title">{{ title }}</text>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            title: 'Hello'
        };
    },
    onLoad() {
        // #ifdef APP-PLUS
        this.getAppImageBase64('/static/logo.png')
            .then(res => {
                console.log(res);
            })
            .catch(err => {
                console.log(err);
            });
        // #endif
        // #ifdef H5
        this.getWebImageBase64_1('https://img.cdn.aliyun.dcloud.net.cn/uni-app/doc/uni-app-frame-0310.png').then(res => {
            console.log('getWebImageBase64_1', res);
        })
        this.getWebImageBase64_2().then(res => {
            console.log('getWebImageBase64_2', res);
        });
        // #endif
    },
    methods: {
        // 支持以下图片路径: 相对路径 - 相对于当前页面的host位置,如"a.jpg",注意当前页面为网络地址则不支持; 绝对路径 - 系统绝对路径,如Android平台"/storage/sdcard0/Android/data/io.dcloud.HBuilder/.HBuilder/apps/HBuilder/www/a.jpg",iOS平台"/var/mobile/Containers/Data/Application/757966CF-345C-4348-B07F-EEF83CF9A369/Library/Pandora/apps/HBuilder/www/a.png"; 相对路径URL(RelativeURL) - 以"_"开头的相对路径,如"_www/a.jpg"、"_doc/b.jpg"、"_documents/c.jpg"、"_downloads/d.jpg"; 本地路径URL - 以“file://”开头,后面跟随系统绝对路径。

        // 平台支持
        // Android - 2.2+ (支持) :
        // 支持jpg/jpeg、png等格式图片。

        // iOS - 5.0+ (支持) :
        // 支持jpg/jpeg、png、tif/tiff、gif、bmp、ico、cur、xbm等格式图片。
        getAppImageBase64(src) {
            return new Promise((resolve, reject) => {
                let base64Data = null;
                plus.zip.compressImage(
                    {
                        src: plus.io.convertLocalFileSystemURL(src),
                        dst: `_doc/temp/${+new Date()}.jpg`,
                        quality: 70
                    },
                    ({ target, size }) => {
                        console.log(target, size);
                        plus.io.resolveLocalFileSystemURL(target, file => {
                            const fileReader = new plus.io.FileReader();
                            fileReader.readAsDataURL(file);
                            fileReader.onloadend = ({ target: { result } }) => {
                                base64Data = result.replace(/^data:image\/\w+;base64,/, '');
                                resolve(base64Data);
                            };
                            fileReader.onerror = err => {
                                console.log('读取文件失败', err);
                            };
                        });
                    },
                    e => {
                        reject(e);
                    }
                );
            });
        },
        getWebImageBase64_1(imgUrl) {
            return new Promise((resolve, reject) => {
                window.URL = window.URL || window.webkitURL;
                let xhr = new XMLHttpRequest();
                xhr.open('get', imgUrl, true);
                // 至关重要
                xhr.responseType = 'blob';
                xhr.onload = function() {
                    if (this.status == 200) {
                        //得到一个blob对象
                        let blob = this.response;
                        console.log('blob', blob);
                        // 至关重要
                        let oFileReader = new FileReader();
                        oFileReader.onloadend = function(e) {
                            let base64 = e.target.result;
                            // console.log('方式一》》》》》》》》》', base64);
                            resolve(base64)
                        };
                        oFileReader.readAsDataURL(blob);
                    }
                };
                xhr.send();
            })
            
        },
        getWebImageBase64_2() {
            let img = 'https://img.cdn.aliyun.dcloud.net.cn/uni-app/doc/uni-app-frame-0310.png'; //imgurl 就是你的图片路径
            function getBase64Image(img) {
                let canvas = document.createElement('canvas');
                canvas.width = img.width;
                canvas.height = img.height;
                let ctx = canvas.getContext('2d');
                ctx.drawImage(img, 0, 0, img.width, img.height);
                let ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase();
                let dataURL = canvas.toDataURL('image/' + ext);
                return dataURL;
            }

            return new Promise((resolve, reject) => {
                let image = new Image();
                image.src = img;
                image.setAttribute("crossOrigin",'Anonymous')
                image.onload = function() {
                    let base64 = getBase64Image(image);
                    // console.log(base64);
                    resolve(base64)
                }
            })
        }
    }
};
</script>

<style>
.content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.logo {
    height: 200rpx;
    width: 200rpx;
    margin-top: 200rpx;
    margin-left: auto;
    margin-right: auto;
    margin-bottom: 50rpx;
}

.text-area {
    display: flex;
    justify-content: center;
}

.title {
    font-size: 36rpx;
    color: #8f8f94;
}
</style>
最后修改:2020 年 12 月 08 日 10 : 40 PM
生活需要一些仪式感,比如手冲一杯咖啡:)