Resolving Smoothing Issues When Resizing Images Using Canvas in JavaScript
Resizing images using canvas in JavaScript can sometimes result in noticeable jagged edges or blurring. To achieve smooth resizes, a technique known as down-stepping can be employed.
In most browsers, linear interpolation is used for resizing by default. Bi-cubic interpolation, which produces smoother results, involves using a larger neighborhood of pixels. However, browsers typically don't implement bi-cubic interpolation directly.
The down-stepping approach involves resizing the image repeatedly, each time using a smaller scale factor. This mimics the behavior of bi-cubic interpolation while still utilizing linear interpolation in the underlying browser.
The following code snippet demonstrates how to implement down-stepping:
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var img = new Image(); img.onload = function () { // set size proportional to image canvas.height = canvas.width * (img.height / img.width); // step 1 - resize to 50% var oc = document.createElement('canvas'), octx = oc.getContext('2d'); oc.width = img.width * 0.5; oc.height = img.height * 0.5; octx.drawImage(img, 0, 0, oc.width, oc.height); // step 2 octx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5); // step 3, resize to final size ctx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5, 0, 0, canvas.width, canvas.height); } img.src = "//i.imgur.com/SHo6Fub.jpg";
This code creates a temporary canvas, oc, and iteratively resizes the image, eventually drawing it onto the final canvas. Each resizing step uses linear interpolation, but by combining them, the overall effect approximates bi-cubic interpolation.
The imageSmoothingQuality property can also be used to control the smoothing quality in Chrome, providing a more direct means of achieving smoothness, but it is not yet supported in all browsers.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3