HTML5 Canvas调整大小(缩小)图像质量如何?

时间:2013-09-20 17:48:59

标签: javascript css html5 canvas html5-canvas

我使用html5 canvas元素在我的浏览器中调整图像大小。事实证明,质量非常低。我发现了这个:Disable Interpolation when Scaling a <canvas>但它无助于提高质量。

下面是我的css和js代码,以及用Photoshop调整并在画布API中缩放的图像。

在浏览器中缩放图片时,我需要做些什么才能获得最佳质量?

注意:我想将大图像缩小为小图像,修改画布中的颜色并将结果从画布发送到服务器。

CSS:

canvas, img {
    image-rendering: optimizeQuality;
    image-rendering: -moz-crisp-edges;
    image-rendering: -webkit-optimize-contrast;
    image-rendering: optimize-contrast;
    -ms-interpolation-mode: nearest-neighbor;
}

JS:

var $img = $('<img>');
var $originalCanvas = $('<canvas>');
$img.load(function() {


   var originalContext = $originalCanvas[0].getContext('2d');   
   originalContext.imageSmoothingEnabled = false;
   originalContext.webkitImageSmoothingEnabled = false;
   originalContext.mozImageSmoothingEnabled = false;
   originalContext.drawImage(this, 0, 0, 379, 500);
});

使用photoshop调整图像大小:

enter image description here

图片在画布上调整大小:

enter image description here

编辑:

我尝试按照以下提议的方式进行缩减:

Resizing an image in an HTML5 canvasHtml5 canvas drawImage: how to apply antialiasing

这是我使用的功能:

function resizeCanvasImage(img, canvas, maxWidth, maxHeight) {
    var imgWidth = img.width, 
        imgHeight = img.height;

    var ratio = 1, ratio1 = 1, ratio2 = 1;
    ratio1 = maxWidth / imgWidth;
    ratio2 = maxHeight / imgHeight;

    // Use the smallest ratio that the image best fit into the maxWidth x maxHeight box.
    if (ratio1 < ratio2) {
        ratio = ratio1;
    }
    else {
        ratio = ratio2;
    }

    var canvasContext = canvas.getContext("2d");
    var canvasCopy = document.createElement("canvas");
    var copyContext = canvasCopy.getContext("2d");
    var canvasCopy2 = document.createElement("canvas");
    var copyContext2 = canvasCopy2.getContext("2d");
    canvasCopy.width = imgWidth;
    canvasCopy.height = imgHeight;  
    copyContext.drawImage(img, 0, 0);

    // init
    canvasCopy2.width = imgWidth;
    canvasCopy2.height = imgHeight;        
    copyContext2.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvasCopy2.width, canvasCopy2.height);


    var rounds = 2;
    var roundRatio = ratio * rounds;
    for (var i = 1; i <= rounds; i++) {
        console.log("Step: "+i);

        // tmp
        canvasCopy.width = imgWidth * roundRatio / i;
        canvasCopy.height = imgHeight * roundRatio / i;

        copyContext.drawImage(canvasCopy2, 0, 0, canvasCopy2.width, canvasCopy2.height, 0, 0, canvasCopy.width, canvasCopy.height);

        // copy back
        canvasCopy2.width = imgWidth * roundRatio / i;
        canvasCopy2.height = imgHeight * roundRatio / i;
        copyContext2.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvasCopy2.width, canvasCopy2.height);

    } // end for


    // copy back to canvas
    canvas.width = imgWidth * roundRatio / rounds;
    canvas.height = imgHeight * roundRatio / rounds;
    canvasContext.drawImage(canvasCopy2, 0, 0, canvasCopy2.width, canvasCopy2.height, 0, 0, canvas.width, canvas.height);


}

如果我使用两步调整大小,结果如下:

enter image description here

如果我使用3步缩小尺寸,结果如下:

enter image description here

如果我使用4步缩小尺寸,结果如下:

enter image description here

如果我使用20步降低尺寸,结果如下:

enter image description here

注意:事实证明,从1步到2步,图像质量有了很大的提高,但是你添加到这个过程的步骤越多,图像就越模糊。

有没有办法解决图片变得越模糊的问题,你添加的步骤越多?

编辑2013-10-04:我尝试了GameAlchemist的算法。这是与Photoshop相比的结果。

PhotoShop图片:

PhotoShop Image

GameAlchemist的算法:

GameAlchemist's Algorithm

14 个答案:

答案 0 :(得分:162)

由于你的问题是缩小你的图像,所以没有必要谈论插值 - 这是关于创建像素 - 。这里的问题是下采样。

要对图像进行下采样,我们需要将原始图像中每个p * p像素的平方转换为目标图像中的单个像素。

出于性能原因,浏览器会进行非常简单的下采样:要构建较小的图像,他们只需在源中选择一个像素并将其值用于目标。 “忘记”一些细节并增加噪音。

然而有一个例外:由于2X图像缩减采样非常简单(平均4个像素制作一个)并用于视网膜/ HiDPI像素,这种情况得到妥善处理 - 浏览器确实使用了4个像素制作一个。

但是......如果您使用多次2X下采样,您将面临连续舍入错误会增加太多噪音的问题。
更糟糕的是,你不会总是以2的幂调整大小,并且调整到最近的功率+最后一次调整大小非常嘈杂。

您所寻求的是一种像素完美的下采样,即:重新采样图像,将所有输入像素考虑在内 - 无论尺度如何.- 为此,我们必须为每个输入像素计算其对一个,两个或四个目标像素的贡献,这取决于输入像素的缩放投影是在目标像素内部,与X边界,Y边界或两者重叠。
(这里的计划很不错,但我没有。)

这是一个画布比例与我在zombat的1/3比例上的像素完美比例的例子。

请注意,图片可能会在您的浏览器中缩放,并且由S.O执行.j .. 然而,我们看到噪音要小得多,特别是在袋熊身后的草地和右边的树枝上。毛皮中的噪音使其更具对比度,但看起来他有白色毛发 - 不像源图片.-
正确的形象不那么吸引人,但确实更好。

enter image description here

这是执行像素完美缩减的代码:

小提琴结果: http://jsfiddle.net/gamealchemist/r6aVp/embedded/result/
摆弄自己:http://jsfiddle.net/gamealchemist/r6aVp/

// scales the image by (float) scale < 1
// returns a canvas containing the scaled image.
function downScaleImage(img, scale) {
    var imgCV = document.createElement('canvas');
    imgCV.width = img.width;
    imgCV.height = img.height;
    var imgCtx = imgCV.getContext('2d');
    imgCtx.drawImage(img, 0, 0);
    return downScaleCanvas(imgCV, scale);
}

// scales the canvas by (float) scale < 1
// returns a new canvas containing the scaled image.
function downScaleCanvas(cv, scale) {
    if (!(scale < 1) || !(scale > 0)) throw ('scale must be a positive number <1 ');
    var sqScale = scale * scale; // square scale = area of source pixel within target
    var sw = cv.width; // source image width
    var sh = cv.height; // source image height
    var tw = Math.floor(sw * scale); // target image width
    var th = Math.floor(sh * scale); // target image height
    var sx = 0, sy = 0, sIndex = 0; // source x,y, index within source array
    var tx = 0, ty = 0, yIndex = 0, tIndex = 0; // target x,y, x,y index within target array
    var tX = 0, tY = 0; // rounded tx, ty
    var w = 0, nw = 0, wx = 0, nwx = 0, wy = 0, nwy = 0; // weight / next weight x / y
    // weight is weight of current source point within target.
    // next weight is weight of current source point within next target's point.
    var crossX = false; // does scaled px cross its current px right border ?
    var crossY = false; // does scaled px cross its current px bottom border ?
    var sBuffer = cv.getContext('2d').
    getImageData(0, 0, sw, sh).data; // source buffer 8 bit rgba
    var tBuffer = new Float32Array(3 * tw * th); // target buffer Float32 rgb
    var sR = 0, sG = 0,  sB = 0; // source's current point r,g,b
    /* untested !
    var sA = 0;  //source alpha  */    

    for (sy = 0; sy < sh; sy++) {
        ty = sy * scale; // y src position within target
        tY = 0 | ty;     // rounded : target pixel's y
        yIndex = 3 * tY * tw;  // line index within target array
        crossY = (tY != (0 | ty + scale)); 
        if (crossY) { // if pixel is crossing botton target pixel
            wy = (tY + 1 - ty); // weight of point within target pixel
            nwy = (ty + scale - tY - 1); // ... within y+1 target pixel
        }
        for (sx = 0; sx < sw; sx++, sIndex += 4) {
            tx = sx * scale; // x src position within target
            tX = 0 |  tx;    // rounded : target pixel's x
            tIndex = yIndex + tX * 3; // target pixel index within target array
            crossX = (tX != (0 | tx + scale));
            if (crossX) { // if pixel is crossing target pixel's right
                wx = (tX + 1 - tx); // weight of point within target pixel
                nwx = (tx + scale - tX - 1); // ... within x+1 target pixel
            }
            sR = sBuffer[sIndex    ];   // retrieving r,g,b for curr src px.
            sG = sBuffer[sIndex + 1];
            sB = sBuffer[sIndex + 2];

            /* !! untested : handling alpha !!
               sA = sBuffer[sIndex + 3];
               if (!sA) continue;
               if (sA != 0xFF) {
                   sR = (sR * sA) >> 8;  // or use /256 instead ??
                   sG = (sG * sA) >> 8;
                   sB = (sB * sA) >> 8;
               }
            */
            if (!crossX && !crossY) { // pixel does not cross
                // just add components weighted by squared scale.
                tBuffer[tIndex    ] += sR * sqScale;
                tBuffer[tIndex + 1] += sG * sqScale;
                tBuffer[tIndex + 2] += sB * sqScale;
            } else if (crossX && !crossY) { // cross on X only
                w = wx * scale;
                // add weighted component for current px
                tBuffer[tIndex    ] += sR * w;
                tBuffer[tIndex + 1] += sG * w;
                tBuffer[tIndex + 2] += sB * w;
                // add weighted component for next (tX+1) px                
                nw = nwx * scale
                tBuffer[tIndex + 3] += sR * nw;
                tBuffer[tIndex + 4] += sG * nw;
                tBuffer[tIndex + 5] += sB * nw;
            } else if (crossY && !crossX) { // cross on Y only
                w = wy * scale;
                // add weighted component for current px
                tBuffer[tIndex    ] += sR * w;
                tBuffer[tIndex + 1] += sG * w;
                tBuffer[tIndex + 2] += sB * w;
                // add weighted component for next (tY+1) px                
                nw = nwy * scale
                tBuffer[tIndex + 3 * tw    ] += sR * nw;
                tBuffer[tIndex + 3 * tw + 1] += sG * nw;
                tBuffer[tIndex + 3 * tw + 2] += sB * nw;
            } else { // crosses both x and y : four target points involved
                // add weighted component for current px
                w = wx * wy;
                tBuffer[tIndex    ] += sR * w;
                tBuffer[tIndex + 1] += sG * w;
                tBuffer[tIndex + 2] += sB * w;
                // for tX + 1; tY px
                nw = nwx * wy;
                tBuffer[tIndex + 3] += sR * nw;
                tBuffer[tIndex + 4] += sG * nw;
                tBuffer[tIndex + 5] += sB * nw;
                // for tX ; tY + 1 px
                nw = wx * nwy;
                tBuffer[tIndex + 3 * tw    ] += sR * nw;
                tBuffer[tIndex + 3 * tw + 1] += sG * nw;
                tBuffer[tIndex + 3 * tw + 2] += sB * nw;
                // for tX + 1 ; tY +1 px
                nw = nwx * nwy;
                tBuffer[tIndex + 3 * tw + 3] += sR * nw;
                tBuffer[tIndex + 3 * tw + 4] += sG * nw;
                tBuffer[tIndex + 3 * tw + 5] += sB * nw;
            }
        } // end for sx 
    } // end for sy

    // create result canvas
    var resCV = document.createElement('canvas');
    resCV.width = tw;
    resCV.height = th;
    var resCtx = resCV.getContext('2d');
    var imgRes = resCtx.getImageData(0, 0, tw, th);
    var tByteBuffer = imgRes.data;
    // convert float32 array into a UInt8Clamped Array
    var pxIndex = 0; //  
    for (sIndex = 0, tIndex = 0; pxIndex < tw * th; sIndex += 3, tIndex += 4, pxIndex++) {
        tByteBuffer[tIndex] = Math.ceil(tBuffer[sIndex]);
        tByteBuffer[tIndex + 1] = Math.ceil(tBuffer[sIndex + 1]);
        tByteBuffer[tIndex + 2] = Math.ceil(tBuffer[sIndex + 2]);
        tByteBuffer[tIndex + 3] = 255;
    }
    // writing result to canvas.
    resCtx.putImageData(imgRes, 0, 0);
    return resCV;
}

相当内存贪婪,因为需要浮点缓冲区来存储目标图像的中间值( - >如果我们计算结果画布,我们使用6倍的源图像内存在这个算法中) 它也非常昂贵,因为无论目标大小如何都使用每个源像素,我们必须支付getImageData / putImageDate,也很慢。
但是在这种情况下,没有办法比处理每个源值更快,情况也不是那么糟糕:对于我的740 * 556袋熊图像,处理时间在30到40毫秒之间。

答案 1 :(得分:46)

高质量的快速画布重新取样:http://jsfiddle.net/9g9Nv/442/

更新版本2.0(更快,网络工作者+可转移对象) - https://github.com/viliusle/Hermite-resize

/**
 * Hermite resize - fast image resize/resample using Hermite filter. 1 cpu version!
 * 
 * @param {HtmlElement} canvas
 * @param {int} width
 * @param {int} height
 * @param {boolean} resize_canvas if true, canvas will be resized. Optional.
 */
function resample_single(canvas, width, height, resize_canvas) {
    var width_source = canvas.width;
    var height_source = canvas.height;
    width = Math.round(width);
    height = Math.round(height);

    var ratio_w = width_source / width;
    var ratio_h = height_source / height;
    var ratio_w_half = Math.ceil(ratio_w / 2);
    var ratio_h_half = Math.ceil(ratio_h / 2);

    var ctx = canvas.getContext("2d");
    var img = ctx.getImageData(0, 0, width_source, height_source);
    var img2 = ctx.createImageData(width, height);
    var data = img.data;
    var data2 = img2.data;

    for (var j = 0; j < height; j++) {
        for (var i = 0; i < width; i++) {
            var x2 = (i + j * width) * 4;
            var weight = 0;
            var weights = 0;
            var weights_alpha = 0;
            var gx_r = 0;
            var gx_g = 0;
            var gx_b = 0;
            var gx_a = 0;
            var center_y = (j + 0.5) * ratio_h;
            var yy_start = Math.floor(j * ratio_h);
            var yy_stop = Math.ceil((j + 1) * ratio_h);
            for (var yy = yy_start; yy < yy_stop; yy++) {
                var dy = Math.abs(center_y - (yy + 0.5)) / ratio_h_half;
                var center_x = (i + 0.5) * ratio_w;
                var w0 = dy * dy; //pre-calc part of w
                var xx_start = Math.floor(i * ratio_w);
                var xx_stop = Math.ceil((i + 1) * ratio_w);
                for (var xx = xx_start; xx < xx_stop; xx++) {
                    var dx = Math.abs(center_x - (xx + 0.5)) / ratio_w_half;
                    var w = Math.sqrt(w0 + dx * dx);
                    if (w >= 1) {
                        //pixel too far
                        continue;
                    }
                    //hermite filter
                    weight = 2 * w * w * w - 3 * w * w + 1;
                    var pos_x = 4 * (xx + yy * width_source);
                    //alpha
                    gx_a += weight * data[pos_x + 3];
                    weights_alpha += weight;
                    //colors
                    if (data[pos_x + 3] < 255)
                        weight = weight * data[pos_x + 3] / 250;
                    gx_r += weight * data[pos_x];
                    gx_g += weight * data[pos_x + 1];
                    gx_b += weight * data[pos_x + 2];
                    weights += weight;
                }
            }
            data2[x2] = gx_r / weights;
            data2[x2 + 1] = gx_g / weights;
            data2[x2 + 2] = gx_b / weights;
            data2[x2 + 3] = gx_a / weights_alpha;
        }
    }
    //clear and resize canvas
    if (resize_canvas === true) {
        canvas.width = width;
        canvas.height = height;
    } else {
        ctx.clearRect(0, 0, width_source, height_source);
    }

    //draw
    ctx.putImageData(img2, 0, 0);
}

答案 2 :(得分:28)

建议1 - 扩展流程管道

您可以像我在您引用的链接中描述的那样使用降压,但您似乎以错误的方式使用它们。

不需要降低步骤以将图像缩放到1:2以上的比例(通常但不限于此)。这是你需要进行剧烈缩小的地方,你需要根据图像的内容将其分成两个(很少,更多)步骤(特别是在高频率如瘦的地方)线条出现。)

每次对图像进行下采样时,都会丢失细节和信息。您不能指望生成的图像与原始图像一样清晰。

如果你在很多步骤中缩小图像,你会丢失很多信息,结果会很差,你已经注意到了。

只需要一个额外的步骤,或者在顶部两个步骤。

卷积

如果Photoshop注意到它在重新采样图像后应用卷积,例如锐化。这不仅仅是双三次插值,所以为了完全模拟Photoshop,我们还需要添加Photoshop正在执行的步骤(使用默认设置)。

对于这个例子,我将使用你在帖子中提到的原始答案,但我已经添加了一个锐化的卷积,以提高后期处理的质量(见底部的演示)。

以下是添加锐化滤镜的代码(它基于通用卷积滤镜 - 我将重量矩阵用于锐化内部以及调整效果发音的混合因子):

<强>用法:

sharpen(context, width, height, mixFactor);

mixFactor是一个介于[0.0,1.0]之间的值,允许你淡化锐化效果 - 经验法则:尺寸越小,需要的效果越少。

功能(基于this snippet):

function sharpen(ctx, w, h, mix) {

    var weights =  [0, -1, 0,  -1, 5, -1,  0, -1, 0],
        katet = Math.round(Math.sqrt(weights.length)),
        half = (katet * 0.5) |0,
        dstData = ctx.createImageData(w, h),
        dstBuff = dstData.data,
        srcBuff = ctx.getImageData(0, 0, w, h).data,
        y = h;

    while(y--) {

        x = w;

        while(x--) {

            var sy = y,
                sx = x,
                dstOff = (y * w + x) * 4,
                r = 0, g = 0, b = 0, a = 0;

            for (var cy = 0; cy < katet; cy++) {
                for (var cx = 0; cx < katet; cx++) {

                    var scy = sy + cy - half;
                    var scx = sx + cx - half;

                    if (scy >= 0 && scy < h && scx >= 0 && scx < w) {

                        var srcOff = (scy * w + scx) * 4;
                        var wt = weights[cy * katet + cx];

                        r += srcBuff[srcOff] * wt;
                        g += srcBuff[srcOff + 1] * wt;
                        b += srcBuff[srcOff + 2] * wt;
                        a += srcBuff[srcOff + 3] * wt;
                    }
                }
            }

            dstBuff[dstOff] = r * mix + srcBuff[dstOff] * (1 - mix);
            dstBuff[dstOff + 1] = g * mix + srcBuff[dstOff + 1] * (1 - mix);
            dstBuff[dstOff + 2] = b * mix + srcBuff[dstOff + 2] * (1 - mix)
            dstBuff[dstOff + 3] = srcBuff[dstOff + 3];
        }
    }

    ctx.putImageData(dstData, 0, 0);
}

使用此组合的结果将是:

<强> ONLINE DEMO HERE

Result downsample and sharpen convolution

根据您想要添加到混合的锐化程度,您可以获得从默认“模糊”到非常清晰的结果:

Variations of sharpen

建议2 - 低级算法实现

如果你想在质量方面获得最好的结果,你需要进行低级别的考虑,并考虑实施这种全新的算法来实现这一目标。

请参阅IEEE的Interpolation-Dependent Image Downsampling(2011) Here is a link to the paper in full (PDF)

目前在JavaScript AFAIK中没有此算法的实现,因此如果您想要完成此任务,那么您就可以完成手动操作。

本质是(摘自论文):

<强>抽象

  

提出了一种面向插值的自适应下采样算法   本文中的低比特率图像编码。鉴于图像,   提出的算法能够从中获得低分辨率图像   这是一个与输入分辨率相同的高质量图像   图像可以插值。与传统不同   下采样算法,独立于   插值过程中,提出的下采样算法取决于   下采样到插值过程。因此,   提出的下采样算法能够保持原始   最大程度地输入图像的信息。下采样   然后将图像输入JPEG。基于总变异(TV)的帖子   然后将处理应用于解压缩的低分辨率图像。   最终,对处理后的图像进行插值以保持图像   输入图像的原始分辨率。 实验结果验证   通过所提出的算法利用下采样图像,   可以实现具有更高质量的插值图像。除了,   所提出的算法能够实现优越的性能   用于低比特率图像编码的JPEG。

Snapshot from paper

(参见提供的所有细节,公式等链接。)

答案 3 :(得分:20)

如果您只想使用画布,最好的结果将是多个缩小步骤。但那还不是很好。为了获得更好的质量,您需要纯js实现。我们刚刚发布了pica - 具有可变质量/速度的高速降尺码器。简而言之,它在~0.1s内调整1280 * 1024px,在1s内调整5000 * 3000px图像,具有最高质量(具有3个波瓣的lanczos滤波器)。 Pica有demo,您可以在其中播放图片,质量等级,甚至可以在移动设备上试用。

Pica还没有不锋利的面具,但很快就会加入。这比实现调整大小的高速卷积滤波器要容易得多。

答案 4 :(得分:17)

为什么要使用画布来调整图像大小?现代浏览器都使用双三次插值 - 与Photoshop使用的相同过程(如果你正确地做) - 并且它们比画布过程更快。只需指定所需的图像大小(仅使用一个维度,高度或宽度,按比例调整大小)。

大多数浏览器都支持此功能,包括IE的更高版本。早期版本may require browser-specific CSS

一个简单的函数(使用jQuery)来调整图像大小如下:

function resizeImage(img, percentage) {
    var coeff = percentage/100,
        width = $(img).width(),
        height = $(img).height();

    return {"width": width*coeff, "height": height*coeff}           
}

然后只需使用返回的值在一个或两个维度中调整图像大小。

显然,您可以进行不同的改进,但这可以完成工作。

将以下代码粘贴到此页面的控制台中,并观察gravatars会发生什么:

function resizeImage(img, percentage) {
    var coeff = percentage/100,
        width = $(img).width(),
        height = $(img).height();

    return {"width": width*coeff, "height": height*coeff}           
}

$('.user-gravatar32 img').each(function(){
  var newDimensions = resizeImage( this, 150);
  this.style.width = newDimensions.width + "px";
  this.style.height = newDimensions.height + "px";
});

答案 5 :(得分:7)

对于真正需要调整图片大小的人来说,不是正确的答案,只是为了缩小文件大小

我直接从相机&#34;&#34;我的客户经常上传的照片&#34;未压缩&#34; JPEG。

不太知名的是,画布支持(在大多数浏览器2017中)改变JPEG的质量

data=canvas.toDataURL('image/jpeg', .85) # [1..0] default 0.92

通过这个技巧,我可以将&gt; 10Mb减少4k x 3k图片到1或2Mb,确定它取决于您的需求。

look here

答案 6 :(得分:4)

这是一个可重复使用的Angular服务,用于高质量的图像/画布调整大小:https://gist.github.com/fisch0920/37bac5e741eaec60e983

该服务支持lanczos卷积和逐步缩减。卷积方法质量较高,代价是较慢,而逐步降尺度方法产生合理的抗锯齿结果,并且速度明显更快。

使用示例:

angular.module('demo').controller('ExampleCtrl', function (imageService) {
  // EXAMPLE USAGE
  // NOTE: it's bad practice to access the DOM inside a controller, 
  // but this is just to show the example usage.

  // resize by lanczos-sinc filter
  imageService.resize($('#myimg')[0], 256, 256)
    .then(function (resizedImage) {
      // do something with resized image
    })

  // resize by stepping down image size in increments of 2x
  imageService.resizeStep($('#myimg')[0], 256, 256)
    .then(function (resizedImage) {
      // do something with resized image
    })
})

答案 7 :(得分:4)

这是改进的Hermite调整大小过滤器,它使用1个工作程序,因此窗口不会冻结。

https://github.com/calvintwr/Hermite-resize

答案 8 :(得分:3)

我找到了一个解决方案,它不需要直接访问像素数据并循环通过它来执行下采样。根据图像的大小,这可能是非常耗费资源的,使用浏览器的内部算法会更好。

drawImage()函数使用线性插值,最近邻重采样方法。当你没有调整大小超过原始大小的一半时,效果很好。

如果循环只能一次调整最多一半,结果会非常好,并且比访问像素数据要快得多。

此功能下采样到一半,直到达到所需的大小:

  function resize_image( src, dst, type, quality ) {
     var tmp = new Image(),
         canvas, context, cW, cH;

     type = type || 'image/jpeg';
     quality = quality || 0.92;

     cW = src.naturalWidth;
     cH = src.naturalHeight;

     tmp.src = src.src;
     tmp.onload = function() {

        canvas = document.createElement( 'canvas' );

        cW /= 2;
        cH /= 2;

        if ( cW < src.width ) cW = src.width;
        if ( cH < src.height ) cH = src.height;

        canvas.width = cW;
        canvas.height = cH;
        context = canvas.getContext( '2d' );
        context.drawImage( tmp, 0, 0, cW, cH );

        dst.src = canvas.toDataURL( type, quality );

        if ( cW <= src.width || cH <= src.height )
           return;

        tmp.src = dst.src;
     }

  }
  // The images sent as parameters can be in the DOM or be image objects
  resize_image( $( '#original' )[0], $( '#smaller' )[0] );

this post

的信用

答案 9 :(得分:1)

也许您可以尝试一下,这是我在项目中经常使用的方法。这样,您不仅可以获取高质量的图像,还可以获取画布上的任何其他元素。

/* 
 * @parame canvas => canvas object
 * @parame rate => the pixel quality
 */
function setCanvasSize(canvas, rate) {
    const scaleRate = rate;
    canvas.width = window.innerWidth * scaleRate;
    canvas.height = window.innerHeight * scaleRate;
    canvas.style.width = window.innerWidth + 'px';
    canvas.style.height = window.innerHeight + 'px';
    canvas.getContext('2d').scale(scaleRate, scaleRate);
}

答案 10 :(得分:0)

DEMO :使用JS和HTML Canvas演示小提琴手调整图像大小。

您可能会发现3种不同的方法来进行此大小调整,这将帮助您了解代码的工作方式以及原因。

https://jsfiddle.net/1b68eLdr/93089/

可以在GitHub项目中找到完整的演示代码以及您可能希望在代码中使用的TypeScript方法。

https://github.com/eyalc4/ts-image-resizer

这是最终代码:

export class ImageTools {
base64ResizedImage: string = null;

constructor() {
}

ResizeImage(base64image: string, width: number = 1080, height: number = 1080) {
    let img = new Image();
    img.src = base64image;

    img.onload = () => {

        // Check if the image require resize at all
        if(img.height <= height && img.width <= width) {
            this.base64ResizedImage = base64image;

            // TODO: Call method to do something with the resize image
        }
        else {
            // Make sure the width and height preserve the original aspect ratio and adjust if needed
            if(img.height > img.width) {
                width = Math.floor(height * (img.width / img.height));
            }
            else {
                height = Math.floor(width * (img.height / img.width));
            }

            let resizingCanvas: HTMLCanvasElement = document.createElement('canvas');
            let resizingCanvasContext = resizingCanvas.getContext("2d");

            // Start with original image size
            resizingCanvas.width = img.width;
            resizingCanvas.height = img.height;


            // Draw the original image on the (temp) resizing canvas
            resizingCanvasContext.drawImage(img, 0, 0, resizingCanvas.width, resizingCanvas.height);

            let curImageDimensions = {
                width: Math.floor(img.width),
                height: Math.floor(img.height)
            };

            let halfImageDimensions = {
                width: null,
                height: null
            };

            // Quickly reduce the size by 50% each time in few iterations until the size is less then
            // 2x time the target size - the motivation for it, is to reduce the aliasing that would have been
            // created with direct reduction of very big image to small image
            while (curImageDimensions.width * 0.5 > width) {
                // Reduce the resizing canvas by half and refresh the image
                halfImageDimensions.width = Math.floor(curImageDimensions.width * 0.5);
                halfImageDimensions.height = Math.floor(curImageDimensions.height * 0.5);

                resizingCanvasContext.drawImage(resizingCanvas, 0, 0, curImageDimensions.width, curImageDimensions.height,
                    0, 0, halfImageDimensions.width, halfImageDimensions.height);

                curImageDimensions.width = halfImageDimensions.width;
                curImageDimensions.height = halfImageDimensions.height;
            }

            // Now do final resize for the resizingCanvas to meet the dimension requirments
            // directly to the output canvas, that will output the final image
            let outputCanvas: HTMLCanvasElement = document.createElement('canvas');
            let outputCanvasContext = outputCanvas.getContext("2d");

            outputCanvas.width = width;
            outputCanvas.height = height;

            outputCanvasContext.drawImage(resizingCanvas, 0, 0, curImageDimensions.width, curImageDimensions.height,
                0, 0, width, height);

            // output the canvas pixels as an image. params: format, quality
            this.base64ResizedImage = outputCanvas.toDataURL('image/jpeg', 0.85);

            // TODO: Call method to do something with the resize image
        }
    };
}}

答案 11 :(得分:0)

如果添加 1.0 ,则

而不是 .85 。您将得到确切的答案。

if

您可以获得清晰明亮的图像。请检查

答案 12 :(得分:0)

我真的试图避免遍历图像数据,尤其是在较大的图像上。因此,我想出了一种相当简单的方法,可以通过一些额外的步骤来适当地减小图像大小,而没有任何限制。 该例程下降到所需目标大小之前的最低半步。然后将其缩放到目标大小的两倍,然后再扩大一半。乍一看听起来很有趣,但结果出奇的好,并且很快就可以解决了。

function resizeCanvas(canvas, newWidth, newHeight) {
  let ctx = canvas.getContext('2d');
  let buffer = document.createElement('canvas');
  buffer.width = ctx.canvas.width;
  buffer.height = ctx.canvas.height;
  let ctxBuf = buffer.getContext('2d');
  

  let scaleX = newWidth / ctx.canvas.width;
  let scaleY = newHeight / ctx.canvas.height;

  let scaler = Math.min(scaleX, scaleY);
  //see if target scale is less than half...
  if (scaler < 0.5) {
    //while loop in case target scale is less than quarter...
    while (scaler < 0.5) {
      ctxBuf.canvas.width = ctxBuf.canvas.width * 0.5;
      ctxBuf.canvas.height = ctxBuf.canvas.height * 0.5;
      ctxBuf.scale(0.5, 0.5);
      ctxBuf.drawImage(canvas, 0, 0);
      ctxBuf.setTransform(1, 0, 0, 1, 0, 0);
      ctx.canvas.width = ctxBuf.canvas.width;
      ctx.canvas.height = ctxBuf.canvas.height;
      ctx.drawImage(buffer, 0, 0);

      scaleX = newWidth / ctxBuf.canvas.width;
      scaleY = newHeight / ctxBuf.canvas.height;
      scaler = Math.min(scaleX, scaleY);
    }
    //only if the scaler is now larger than half, double target scale trick...
    if (scaler > 0.5) {
      scaleX *= 2.0;
      scaleY *= 2.0;
      ctxBuf.canvas.width = ctxBuf.canvas.width * scaleX;
      ctxBuf.canvas.height = ctxBuf.canvas.height * scaleY;
      ctxBuf.scale(scaleX, scaleY);
      ctxBuf.drawImage(canvas, 0, 0);
      ctxBuf.setTransform(1, 0, 0, 1, 0, 0);
      scaleX = 0.5;
      scaleY = 0.5;
    }
  } else
    ctxBuf.drawImage(canvas, 0, 0);

  //wrapping things up...
  ctx.canvas.width = newWidth;
  ctx.canvas.height = newHeight;
  ctx.scale(scaleX, scaleY);
  ctx.drawImage(buffer, 0, 0);
  ctx.setTransform(1, 0, 0, 1, 0, 0);
}

答案 13 :(得分:-1)

context.scale(xScale, yScale)

<canvas id="c"></canvas>
<hr/>
<img id="i" />

<script>
var i = document.getElementById('i');

i.onload = function(){
    var width = this.naturalWidth,
        height = this.naturalHeight,
        canvas = document.getElementById('c'),
        ctx = canvas.getContext('2d');

    canvas.width = Math.floor(width / 2);
    canvas.height = Math.floor(height / 2);

    ctx.scale(0.5, 0.5);
    ctx.drawImage(this, 0, 0);
    ctx.rect(0,0,500,500);
    ctx.stroke();

    // restore original 1x1 scale
    ctx.scale(2, 2);
    ctx.rect(0,0,500,500);
    ctx.stroke();
};

i.src = 'https://static.md/b70a511140758c63f07b618da5137b5d.png';
</script>