Skip to content

Commit

Permalink
Better Jpeg downscaling image quality
Browse files Browse the repository at this point in the history
  • Loading branch information
fkaelberer committed Mar 4, 2016
1 parent ec1cf28 commit 913d3bc
Showing 1 changed file with 28 additions and 5 deletions.
33 changes: 28 additions & 5 deletions src/display/canvas.js
Original file line number Diff line number Diff line change
Expand Up @@ -1892,8 +1892,31 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
// scale the image to the unit square
ctx.scale(1 / w, -1 / h);

ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
0, -h, w, h);
var targetW = ctx.canvas.width;
var targetH = ctx.canvas.height;
var tmpCanvasId = 'prescale1';
var imgToPaint = domImage;
var imgW = domImage.width;
var imgH = domImage.height;

// Vertical or horizontal scaling shall not be more than 2 to not loose
// the pixels during drawImage operation, painting on the temporary
// canvas(es) that are twice smaller in size
while ((imgW > 2 * targetW) || (imgH > 2 * targetH)) {
var newW = Math.ceil(imgW / 2);
var newH = Math.ceil(imgH / 2);

var tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newW, newH);
tmpCanvas.context.clearRect(0, 0, newW, newH);
tmpCanvas.context.drawImage(imgToPaint, 0, 0, imgW, imgH,
0, 0, newW, newH);
imgW = newW;
imgH = newH;
imgToPaint = tmpCanvas.canvas;
tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
}
ctx.drawImage(imgToPaint, 0, 0, imgW, imgH, 0, -h, w, h);

if (this.imageLayer) {
var currentTransform = ctx.mozCurrentTransformInverse;
var position = this.getCanvasPosition(0, 0);
Expand Down Expand Up @@ -2075,9 +2098,9 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {

var paintWidth = width, paintHeight = height;
var tmpCanvasId = 'prescale1';
// Vertial or horizontal scaling shall not be more than 2 to not loose the
// pixels during drawImage operation, painting on the temporary canvas(es)
// that are twice smaller in size
// Vertical or horizontal scaling shall not be more than 2 to not loose
// the pixels during drawImage operation, painting on the temporary
// canvas(es) that are twice smaller in size
while ((widthScale > 2 && paintWidth > 1) ||
(heightScale > 2 && paintHeight > 1)) {
var newWidth = paintWidth, newHeight = paintHeight;
Expand Down

0 comments on commit 913d3bc

Please sign in to comment.