From 8c093f2c724fe9fd58d6c111212254354fe9e455 Mon Sep 17 00:00:00 2001 From: MoonFlyer Date: Sat, 8 Aug 2015 17:49:17 +0800 Subject: [PATCH] add down scale function for thumb (better quality) --- image-resizer.js | 41 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/image-resizer.js b/image-resizer.js index d3ed31b..9d89439 100644 --- a/image-resizer.js +++ b/image-resizer.js @@ -32,6 +32,45 @@ IR.ImageResizer = (function() { return canvas.toDataURL(); }; + + var thumb = function(image, maxWidth, maxHeight) { + + var cwidth = 0; + var cheight = 0; + // set the correct accepted dimensions on the canvas + if (image.width > image.height) { + if (image.width > maxWidth) { + cheight = image.height * maxWidth / image.width; // maintain aspect ratio + cwidth = maxWidth; + } + } else { + if (image.height > maxHeight) { + cwidth = image.width * maxHeight / image.height; + cheight = maxHeight; + } + } + + // Step it down several times + var can2 = document.createElement('canvas'); + can2.width = cwidth*8; + can2.height = cheight*8; + var ctx2 = can2.getContext('2d'); + + // Draw it at 1/2 size 3 times (step down three times) + + ctx2.drawImage(img, 0, 0, cwidth*4, cheight*4); + ctx2.drawImage(can2, 0, 0, cwidth*4, cheight*4, 0, 0, cwidth*2, cheight*2); + ctx2.drawImage(can2, 0, 0, cwidth*2, cheight*2, 0, 0, cwidth, cheight); + + + var can = document.getElementById('canvas1'); + can.width = cwidth; + can.height = cheight; + var ctx = can.getContext('2d'); + ctx.drawImage(can2, 0, 0, cwidth, cheight, 0, 0, cwidth, cheight); + + return can.toDataURL(); + }; /* * Converts a data URI object to a Blob object @@ -55,4 +94,4 @@ IR.ImageResizer = (function() { toBlob: toBlob }; -})(); \ No newline at end of file +})();