Unravel image processing recursion and fix bugs

Although I find the previous implementation more elegant, it results in
a deeper nesting of Promises than necessary, which can make debugging
more complicated. The canvas scaling and compression apis are actually
synchronous, so the callback structure isn't really recessary here.
Converting to a loop also makes this process easier to understand at
a glance.

Fixed some bugs along the way:
* accidentally scaling small images up to 1920px
* jpeg compressing gifs and other formats even if unnecessary
pull/749/head
lilia 10 years ago
parent 0da04632f2
commit 7c9ad975bb

@ -53,36 +53,45 @@ var Whisper = Whisper || {};
} }
return new Promise(function(resolve, reject) { return new Promise(function(resolve, reject) {
// components/blueimp-load-image var url = URL.createObjectURL(file);
window.loadImage(file, resolve, { var img = document.createElement('img');
maxWidth: 1920, img.onerror = reject;
maxHeight: 1920, img.onload = function () {
canvas: true, URL.revokeObjectURL(url);
contain: true
}); var maxSize = 420 * 1024;
}).then(this.autoCompress.bind(this)); var maxHeight = 1920;
}, var maxWidth = 1920;
if (img.width <= maxWidth && img.height <= maxHeight &&
autoCompress: function(canvas, numRetries, quality) { file.size <= maxSize) {
if (numRetries === undefined) { numRetries = 3; } resolve(file);
if (quality === undefined) { quality = 0.95; } return;
}
var autoCompress = this.autoCompress.bind(this);
return new Promise(function(resolve, reject) { // loadImage.scale -> components/blueimp-load-image
canvas.toBlob(function(blob) { var canvas = loadImage.scale(img, {
var kb = blob.size/1024; canvas: true, maxWidth: 1920, maxHeight: 1920
if (kb < 420 || numRetries === 0) { });
resolve(blob);
} else { var quality = 0.95;
quality = quality * 420 / kb; var i = 4;
var blob;
do {
i = i - 1;
// dataURLtoBlob -> components/blueimp-canvas-to-blob
blob = dataURLtoBlob(
canvas.toDataURL('image/jpeg', quality)
);
quality = quality * maxSize / blob.size;
if (quality < 50) { if (quality < 50) {
quality = 50; quality = 50;
numRetries = 1; i = 1;
} }
resolve(autoCompress(canvas, numRetries - 1, quality)); } while (i > 0 && blob.size > maxSize);
}
}, 'image/jpeg', quality); resolve(blob);
};
img.src = url;
}); });
}, },

Loading…
Cancel
Save