問題:
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:
解決方案:
參考一: https://stackoom.com/question/9fII參考二: Resizing an image in an HTML5 canvas