【发布时间】:2012-12-05 16:51:03
【问题描述】:
我正在制作和上传带有客户端图像大小的页面(使用 HTML5 画布)。一切正常,但问题是图像质量不是很好。
Here is a link 到(正在进行的)照片库,其中包含我的调整大小/上传代码生成的图像。
你明白我说的质量差是什么意思吗?许多锯齿状边缘,尤其是在缩略图图像上。有关如何解决此问题的任何想法?
这是我用于生成缩略图的 javascript:
img.onload = function()
{
var canvasWidth = 150;
var canvasHeight = 150;
var Rz = resizeCanvasSmall(img,canvasID,canvasWidth,canvasHeight);
ctx.drawImage(img,Rz[0],Rz[1],Rz[2],Rz[3],Rz[4],Rz[5],Rz[6],Rz[7]);
dataurl = canvas.toDataURL("image/jpeg",0.8); // File type and quality (0.0->1.0)
UploadFile();
}
// Function to resize canvas (for thumbnail images)
// img = image object, canvas = canvas element ID
function resizeCanvasSmall(img,canvas,width,height)
{
var sx; //The x coordinate where to start clipping
var sy; //The y coordinate where to start clipping
var swidth; //The width of the clipped image
var sheight; //The height of the clipped image
var aspectRatio = width / height;
if (img.width > img.height) // If landscape
{
sheight = img.height;
swidth = img.height * aspectRatio;
sy = 0;
sx = (img.width - swidth) / 2;
}
else //If portrait
{
swidth = img.width;
sheight = img.width / aspectRatio;
sx = 0;
sy = (img.height - sheight) / 2;
}
document.getElementById(canvas).width = width;
document.getElementById(canvas).height = height;
return [sx,sy,swidth,sheight,0,0,width,height];
}
【问题讨论】:
-
我在图像中注意到的第一件事 - 调整大小不合适。我的意思是原始图像(W1,H1)缩略图(W2,H2)。如果 (W1/W2 == H1/H2) 你会得到更好的结果
-
这个标准没有指定drawImage使用的缩放算法,所以浏览器可以使用任何他们想要的。当您需要高级图像过滤(例如 lanczos 上的双三次、sinc)时,您必须自己实现它们。
-
你可能是对的 (W1/W2 == H1/H2) @Joddy。我猜如果原始图像是 3241x2321 像素(例如),那么当您将图像缩小时,您将无法完美地保持纵横比。我会尝试编写一些代码,首先将图像剪辑成可以缩小的大小......如果它有效,会告诉你。
-
Jcrop 也是另一个不错的图片上传 jQuery 插件。 deepliquid.com/content/Jcrop.html
标签: javascript html canvas