Note that there are some explanatory texts on larger screens.

plurals
  1. POResizing an image in an HTML5 canvas
    text
    copied!<p>I'm trying to create a thumbnail image on the client side using javascript and a canvas element, but when I shrink the image down, it looks terrible. It looks as if it was downsized in photoshop with the resampling set to 'Nearest Neighbor' instead of Bicubic. I know its possible to get this to look right, because <a href="http://editor.pixastic.com/" rel="noreferrer">this site</a> can do it just fine using a canvas as well. I've tried using the same code they do as shown in the "[Source]" link, but it still looks terrible. Is there something I'm missing, some setting that needs to be set or something?</p> <p>EDIT:</p> <p>I'm trying to resize a jpg. I have tried resizing the same jpg on the linked site and in photoshop, and it looks fine when downsized.</p> <p>Here is the relevant code:</p> <pre><code>reader.onloadend = function(e) { var img = new Image(); var ctx = canvas.getContext("2d"); var canvasCopy = document.createElement("canvas"); var copyContext = canvasCopy.getContext("2d"); img.onload = function() { var ratio = 1; if(img.width &gt; maxWidth) ratio = maxWidth / img.width; else if(img.height &gt; maxHeight) ratio = maxHeight / img.height; canvasCopy.width = img.width; canvasCopy.height = img.height; copyContext.drawImage(img, 0, 0); canvas.width = img.width * ratio; canvas.height = img.height * ratio; ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height); }; img.src = reader.result; } </code></pre> <p>EDIT2:</p> <p>Seems I was mistaken, the linked website wasn't doing any better of a job of downsizing the image. I tried the other methods suggested and none of them look any better. This is what the different methods resulted in:</p> <p>Photoshop:</p> <p><img src="https://i.stack.imgur.com/K6ztq.png" alt="alt text"></p> <p>Canvas:</p> <p><img src="https://i.stack.imgur.com/nD3FJ.png" alt="alt text"></p> <p>Image with image-rendering: optimizeQuality set and scaled with width/height:</p> <p><img src="https://i.stack.imgur.com/I6RkV.png" alt="alt text"></p> <p>Image with image-rendering: optimizeQuality set and scaled with -moz-transform:</p> <p><img src="https://i.stack.imgur.com/ZWiVC.png" alt="alt text"></p> <p>Canvas resize on pixastic:</p> <p><img src="https://i.stack.imgur.com/PEsYM.png" alt="alt text"></p> <p>I guess this means firefox isn't using bicubic sampling like its supposed to. I'll just have to wait until they actually add it.</p> <p>EDIT3:</p> <p><a href="https://i.stack.imgur.com/5x1UP.jpg" rel="noreferrer">Original Image</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload