canvas的drawImage方法, 会使图片的质量变大, 怎么解决?

我的原图是这个image.png
我用drawImage后, 图片是这个image.png
这是我的代码

 let ctx = uni.createCanvasContext("firstCanvas");
                    let date = `时间: ${uni.$u.timeFormat(
                        Date.now(),
                        "yyyy-mm-dd hh:MM:ss"
                    )}`;
                    let address = that.locationAddress;
                    let textWidth = ctx.measureText(date).width;
                    let imgWidth = ress.width;
                    let imgHeight = ress.height;
                    that.canvasWdith = imgWidth;
                    that.canvasHeight = imgHeight;
                    console.log(1111, ress);
                    //将图片src放到cancas内,宽高为图片大小
                    ctx.drawImage(path, 0, 0, imgWidth, imgHeight);
                    ctx.rect(0, imgHeight - 150, imgWidth, 160);
                    ctx.fillStyle = "rgba(0, 0, 0, 0.5)";
                    ctx.fill();
                    //将声明的时间放入canvas
                    ctx.setFontSize(50); //注意:设置文字大小必须放在填充文字之前,否则不生效
                    ctx.setFillStyle("white");
                    ctx.fillText(date, 0, imgHeight - 100); //水印内容,位置
                    ctx.fillText(address, 0, imgHeight - 40); //水印内容,位置
                    // ctx.strokeText(date, 500, 500);

                    uni.showLoading({
                        title: "制作水印中...",
                    });
                    ctx.draw(false, async (res) => {
                        console.log('44444', res);
                        //开始制作
                        if (res && res.errMsg == "drawCanvas:ok") {
                            await new Promise((resolve) => {
                                setTimeout(() => resolve(true), 500);
                            })
                            that.canvasToImg()
                        } else {
                            uni.hideLoading();
                            uni.showToast({
                                icon: "error",
                                title: "制作水印失败",
                            });
                        }
                    });
阅读 3.7k
1 个回答

很正常啊,因为你原来的jpg图片是(有损)压缩的,在canvas显示时是需要解压缩,再处理。

这样处理最后再保存的时候,如果压缩等级不同,出现更大(更小)都是可能的。

这个和保存数据的模式、类型等等都是有关的。

你的代码中没有提醒这一部分内容。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题