使用 javascript 画布调整图像大小(平滑) [英] Resize image with javascript canvas (smoothly)

查看:33
本文介绍了使用 javascript 画布调整图像大小(平滑)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用画布调整一些图像的大小,但我对如何平滑它们一无所知.在 photoshop、浏览器等上,他们使用了一些算法(例如双三次、双线性),但我不知道这些是否内置在画布中.

I'm trying to resize some images with canvas but I'm clueless on how to smoothen them. On photoshop, browsers etc.. there are a few algorithms they use (e.g. bicubic, bilinear) but I don't know if these are built into canvas or not.

这是我的小提琴:http://jsfiddle.net/EWupT/

var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width=300
canvas.height=234
ctx.drawImage(img, 0, 0, 300, 234);
document.body.appendChild(canvas);

第一个是普通调整大小的图像标签,第二个是画布.请注意画布是如何不平滑的.我怎样才能达到平滑"?

The first one is a normal resized image tag, and the second one is canvas. Notice how the canvas one is not as smooth. How can I achieve 'smoothness'?

推荐答案

您可以使用降级来获得更好的结果.大多数浏览器似乎在调整图像大小时使用线性插值而不是双三次插值.

You can use down-stepping to achieve better results. Most browsers seem to use linear interpolation rather than bi-cubic when resizing images.

(更新在规范中添加了一个质量属性,imageSmoothingQuality 目前仅在 Chrome 中可用.)

(Update There has been added a quality property to the specs, imageSmoothingQuality which is currently available in Chrome only.)

除非选择不平滑或最近邻,否则浏览器将始终在缩小图像后插入图像,因为此功能作为低通滤波器以避免混叠.

Unless one chooses no smoothing or nearest neighbor the browser will always interpolate the image after down-scaling it as this function as a low-pass filter to avoid aliasing.

双线性使用 2x2 像素进行插值,而双三次使用 4x4,因此通过分步进行,您可以在使用双线性插值时接近双三次结果,如结果图像所示.

Bi-linear uses 2x2 pixels to do the interpolation while bi-cubic uses 4x4 so by doing it in steps you can get close to bi-cubic result while using bi-linear interpolation as seen in the resulting images.

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";

<img src="//i.imgur.com/SHo6Fub.jpg" width="300" height="234">
<canvas id="canvas" width=300></canvas>

根据您调整大小的剧烈程度,如果差异较小,您可以跳过第 2 步.

Depending on how drastic your resize is you can might skip step 2 if the difference is less.

在演示中,您可以看到新结果现在与图像元素非常相似.

In the demo you can see the new result is now much similar to the image element.

这篇关于使用 javascript 画布调整图像大小(平滑)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆