gpt4 book ai didi

javascript - 使用 Canvas 下载图像会增加文件的大小

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:58:11 27 4
gpt4 key购买 nike

当我尝试使用 Canvas 处理图像时,没有任何修改,我的图像文件大小变得比原始文件大得多。

您能解释一下为什么会发生这种情况以及我该如何避免这种情况吗?

https://jsfiddle.net/95rnh4yj/

function one(selector) {
return document.querySelector(selector);
}

function on(element, event, listener) {
element.addEventListener(event, listener);
}

function blobToUrl(blob) {
return Promise.resolve(URL.createObjectURL(blob));
}

function urlToImg(url) {
return new Promise(function (resolve) {
let
img = new Image();

img.src = url;

on(img, 'load', function (event) {
resolve(event.target);
});
});
}

function imgToBlob(img) {
return new Promise(function (resolve) {
let
canvas = document.createElement('canvas'),
context = canvas.getContext('2d');

canvas.height = img.naturalHeight;
canvas.width = img.naturalWidth;
context.fillStyle = 'transparent';
context.fillRect(0, 0, canvas.width, canvas.height);
context.save();
context.drawImage(img, 0, 0);
canvas.toBlob(resolve, 'image/jpeg', 1);
});
}

function writeSrc(src) {
one('a').href = src;
}

on(one('input'), 'change', function(event) {
blobToUrl(event.target.files[0])
.then(urlToImg)
.then(imgToBlob)
.then(blobToUrl)
.then(writeSrc);
})

最佳答案

如果您的问题是文件大小,请更改您的质量设置。
当前您将其设置为 100。将其更改为例如0.95

function imgToBlob(img) {
return new Promise(function (resolve) {
let
canvas = document.createElement('canvas'),
context = canvas.getContext('2d');

canvas.height = img.naturalHeight;
canvas.width = img.naturalWidth;
context.fillStyle = 'transparent';
context.fillRect(0, 0, canvas.width, canvas.height);
context.save();
context.drawImage(img, 0, 0);
canvas.toBlob(resolve, 'image/jpeg', 0.95); // <-----
});
}

Try to omit the quality setting and see if this works:

function imgToBlob(img) {
return new Promise(function (resolve) {
let
canvas = document.createElement('canvas'),
context = canvas.getContext('2d');

canvas.height = img.naturalHeight;
canvas.width = img.naturalWidth;
context.fillStyle = 'transparent';
context.fillRect(0, 0, canvas.width, canvas.height);
context.save();
context.drawImage(img, 0, 0);
canvas.toBlob(resolve, 'image/jpeg');
});
}

省略质量设置对我来说效果最好 (Jsfiddle)。

148kb -> 154kb (jpeg to jpeg)
102kb -> 119Kb

关于javascript - 使用 Canvas 下载图像会增加文件的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48923404/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com