美文网首页前端
微信小程序图片压缩且转换为base64

微信小程序图片压缩且转换为base64

作者: 匆匆那年_海 | 来源:发表于2019-04-24 12:34 被阅读0次

小程序将图片转换为base64
方法一真机下会出错报无效的路径
方法二测试有效(压缩大不建议使用)
方法三旧版本,测试有效(建议使用)
方法四2.9.0 起支持一套新 Canvas 2D 接口,测试有效(强烈建议使用)

方法一:真机下会出错报无效的路径(不可用)
request:fail invalid url "wxfile://tmp_7c6025b86ad385c609d0094facbeb1c7ca426dc83b33e628.jpg"

wx.request({
        url: temp,//临时路径
        responseType: 'arraybuffer', //设置返回的数据格式为arraybuffer
        success: res => {
                const base64 = wx.arrayBufferToBase64(res.data)},
    })
方法二测试有效(压缩大不建议使用)
drawCanvas(callBack) {
loadings('压缩图片中');
// 获取屏幕宽度
wx.getSystemInfo({
    success: res => {
        console.log(res)
        let windowWidth = res.windowWidth;
        // 获取图片信息
        wx.getImageInfo({
            src: this.data.imgPath,
            success: res => {
                console.log('img', res)
                // 比例
                var scale = 1;
                if (res.width > windowWidth) {
                    scale = windowWidth / res.width;
                }
                // 宽
                let imgWidth = res.width * scale;
                // 高
                let imgHeight = res.height * scale;
                // 画布大小
                this.setData({
                    canvasWidth: imgWidth,
                    canvasHeight: imgHeight
                })
                const ctx = wx.createCanvasContext('myCanvas');
                // 绘制图像到画布
                ctx.drawImage(this.data.imgPath, 0, 0, imgWidth, imgHeight);
                // 将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中。
                ctx.draw(false, setTimeout(() => {
                    // 把当前画布指定区域的内容导出生成指定大小的图片。在 draw() 回调里调用该方法才能保证图片导出成功。
                    wx.canvasToTempFilePath({
                        x: 0,
                        y: 0,
                        width: imgWidth,
                        height: imgHeight,
                        fileType: 'png',
                        canvasId: 'myCanvas',
                        success: (res) => {
                            // 读取本地文件内容
                            wx.getFileSystemManager().readFile({
                                filePath: res.tempFilePath,
                                encoding: 'base64',
                                success: res => {
                                    callBack(res.data);
                                },
                                fail: err => {
                                    console.log(err);
                                }
                            })
                        },
                        fail: err => {
                            wx.hideLoading();
                            modal('压缩图片失败,请稍后重试!');
                        }
                    })
                }, 1000));
            },
            fail: err => {
                console.log(err);
                modal('获取图片信息失败,请稍后重试!');
            }
        })
    }
})

},

方法三旧版本,测试有效(建议使用)

UPNG.js和pako.min.js同级目录 只要引入UPNG.js
下载地址 UPNG.js和pako.min.js

<canvas canvas-id="myCanvas" style="width:{{canvasWidth}}px;height:
{{canvasHeight}}px;position:fixed;top:-9999px;left:-9999px"></canvas>
import upng from '../../static/UPNG.js'
wx.getSystemInfo({
    success: res => {
        let windowWidth = res.windowWidth;
        // 获取图片信息
        wx.getImageInfo({
            src: this.data.imgPath,
            success: res => {
                // 比例
                var scale = 1;
                if (res.width > windowWidth) {
                    scale = windowWidth / res.width;
                }
                console.log(scale);
                // 宽
                let imgWidth = res.width * scale;
                // 高
                let imgHeight = res.height * scale;
                //设置canvas标签宽高
                this.setData({
                    canvasWidth: imgWidth,
                    canvasHeight: imgHeight
                })
                // 将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中。
                const ctx = wx.createCanvasContext('myCanvas');
                ctx.drawImage(this.data.imgPath, 0, 0, imgWidth, imgHeight);
                ctx.draw(false, setTimeout(() => {
                    //获取 canvas 区域隐含的像素数据
                    wx.canvasGetImageData({
                        canvasId: 'myCanvas',
                        x: 0,
                        y: 0,
                        width: imgWidth,
                        height: imgHeight,
                        success: (res) => {
                            const pngData = upng.encode([res.data.buffer], res.width, res.height);
                            const base64 = wx.arrayBufferToBase64(pngData);
                            callBack(base64);
                        },
                        fail: err => {
                            modal('压缩图片失败,请稍后重试!');
                        }
                    })
                }, 1000));
            },
            fail: err => {
                console.log(err);
                modal('获取图片信息失败,请稍后重试!');
            }
        })
    }
})

方法四2.9.0 起支持一套新 Canvas 2D 接口,测试有效(强烈建议建议使用)
<canvas id="myCanvas" type="2d" style="width:{{canvasWidth}}px;height:
{{canvasHeight}}px;position:fixed;top:-9999px;left:-9999px"></canvas>
wx.getSystemInfo({
    success: res => {
        let windowWidth = res.windowWidth;
        // 获取图片信息
        wx.getImageInfo({
            src: this.data.imgPath,
            success: res => {
                // 比例
                var scale = 1;
                if (res.width > windowWidth) {
                    scale = windowWidth / res.width;
                }
                console.log(scale);
                // 宽
                let imgWidth = res.width * scale;
                // 高
                let imgHeight = res.height * scale;
                //设置canvas标签宽高
                this.setData({
                    canvasWidth: imgWidth,
                    canvasHeight: imgHeight
                })
                //获取canvas-----------------------------------------
                const query = wx.createSelectorQuery();
                query.select('#myCanvas').fields({
                    node: true,
                    size: true
                }).exec(async res => {
                    const canvas = res[0].node;
                    canvas.width = imgWidth;
                    canvas.height = imgHeight;
                    //2d画布
                    const ctx = canvas.getContext('2d');
                    //创建图片
                    const mainImg = canvas.createImage();
                    mainImg.src = this.data.imgPath;
                    const mainImgs = await new Promise((resolve, reject) => {
                        mainImg.onload = () => resolve(mainImg);
                        mainImg.onerror = (e) => reject(e);
                    });
                    // 绘制图像到画布
                    ctx.drawImage(mainImgs, 0, 0, imgWidth, imgHeight);
                    let base64 = canvas.toDataURL('image/jpeg', 0.9).replace('data:image/jpeg;base64,', "");
                    callBack(base64);
                })
            },
            fail: err => {
                console.log(err);
                modal('获取图片信息失败,请稍后重试!');
            }
        })
    }
})


原文作者:匆匆那年_海,博客主页:https://www.jianshu.com/u/910c0667c515
95后前端汉子,爱编程、优秀、聪明、理性、沉稳、智慧的程序猿一枚。

相关文章

网友评论

    本文标题:微信小程序图片压缩且转换为base64

    本文链接:https://www.haomeiwen.com/subject/uqzwgqtx.html