在 HTML5 画布中调整图像大小 - Resizing an image in an HTML5 canvas

问题:

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.我正在尝试使用 javascript 和 canvas 元素在客户端创建一个缩略图图像,但是当我缩小图像时,它看起来很糟糕。 It looks as if it was downsized in photoshop with the resampling set to 'Nearest Neighbor' instead of Bicubic.它看起来好像在 Photoshop 中缩小了尺寸,重采样设置为“最近的邻居”而不是双三次。 I know its possible to get this to look right, because this site 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.我尝试使用与“[Source]”链接中所示相同的代码,但它看起来仍然很糟糕。 Is there something I'm missing, some setting that needs to be set or something?有什么我遗漏的,需要设置的一些设置还是什么?

EDIT:编辑:

I'm trying to resize a jpg.我正在尝试调整 jpg 的大小。 I have tried resizing the same jpg on the linked site and in photoshop, and it looks fine when downsized.我尝试在链接的网站和 photoshop 中调整相同的 jpg 大小,缩小后看起来不错。

Here is the relevant 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 > maxWidth)
            ratio = maxWidth / img.width;
        else if(img.height > 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;
}

EDIT2:编辑2:

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:这就是不同的方法导致的结果:

Photoshop: Photoshop:

替代文字

Canvas:帆布:

替代文字

Image with image-rendering: optimizeQuality set and scaled with width/height:带有图像渲染的图像:优化质量设置并按宽度/高度缩放:

替代文字

Image with image-rendering: optimizeQuality set and scaled with -moz-transform:带有图像渲染的图像:优化质量设置并使用 -moz-transform 缩放:

替代文字

Canvas resize on pixastic:画布在 pixastic 上调整大小:

替代文字

I guess this means firefox isn't using bicubic sampling like its supposed to.我想这意味着 firefox 没有像它应该的那样使用双三次采样。 I'll just have to wait until they actually add it.我只需要等到他们真正添加它。

EDIT3:编辑3:

Original Image原图


解决方案:

参考一: https://stackoom.com/question/9fII
参考二: Resizing an image in an HTML5 canvas
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章