変更を加えずにキャンバスを使用して画像を操作しようとすると、画像のファイルサイズが元の画像よりも大幅に大きくなります。
なぜこれが起こるのか、どうすればこれを回避できるのか説明していただけますか?
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); // <-----
});
}
品質設定を省略して、これが機能するかどうかを確認してください。
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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加