Skip to content

Instantly share code, notes, and snippets.

@drewdaemon
Last active May 13, 2022 12:58
Show Gist options
  • Save drewdaemon/8b082dc5abedf82a1635d2792e097e3f to your computer and use it in GitHub Desktop.
Save drewdaemon/8b082dc5abedf82a1635d2792e097e3f to your computer and use it in GitHub Desktop.
Front end JS for generating image thumbnails from base64-encoded images.
function ThumbnailGenerator() {
this.resizeCanvas = document.createElement('canvas');
this.generate = function (imgSrc, thumbDims, compression) {
[this.resizeCanvas.width, this.resizeCanvas.height] = [thumbDims.x, thumbDims.y];
const ctx = this.resizeCanvas.getContext("2d");
const tmp = new Image();
const ret = new Promise(resolve => {
tmp.onload = () => {
ctx.drawImage(tmp, 0, 0, thumbDims.x, thumbDims.y);
resolve(this.resizeCanvas.toDataURL('image/jpeg', compression || 0.5));
};
});
tmp.src = imgSrc;
return ret;
};
this.generateBatch = function (imgSrcs, thumbDims, compression) {
return Promise.all(imgSrcs.map(img => this.generate(img, thumbDims, compression)));
}
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment