HTML5画布调整尺寸(下限值)图像高品质?

问题描述 投票:143回答:12

我使用HTML5画布元素来调整图像即时我的浏览器。事实证明,质量是非常低的。我发现这一点: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调整图像:

调整在画布上的图像:

编辑:

我试图让一个以上的步骤缩减为中提出:

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


}

下面是结果,如果我用一个2降压大小:

下面是结果,如果我用一个3降压大小:

下面是结果,如果我用一个4降压大小:

下面是结果,如果我用一个20降压大小:

注:事实证明,从1步2步存在图像质量的大改善,但您添加到进程中发挥更模糊图像变得更加步骤。

有没有办法解决这个问题的方式,图像变得更模糊了更多的步骤,你补充的吗?

编辑2013年10月4日:我试图GameAlchemist的算法。这是相比于Photoshop的结果。

Photoshop图像:

GameAlchemist的算法:

javascript css html5 canvas html5-canvas
12个回答
166
投票

由于您的问题是,以缩减你的形象,还有在谈及插首位,而其有关创建像素 - 没有意义的。这里的问题是采样。

下采样的图像,我们需要把P * p个像素的每个正方形在原始图像中到目标图像中的单个像素。

对于演出的原因浏览器做一个很简单的采样:打造较小的图像,他们会随便挑一个像素源和使用它的价值为目标。这“忘记”了一些细节,并增加了噪音。

然而,有一个例外,即:自2X图像采样是非常简单的计算(平均4个像素进行一次),用于视网膜/ HiDPI像素,这种情况下,妥善处理-the浏览器不使用的4个像素进行一-。

但是...如果你使用几个时间2X采样,你要面对的是连续的舍入误差会增加太多的噪音问题。 更糟的是,你不会总是由二的幂调整,并调整到最近的电源+最后的大小调整是非常嘈杂。

你追求什么是完美的像素下采样,即:将采取所有输入像素考虑-whatever的横向扩展图像的重采样。 要做到这一点,我们必须计算,每个输入像素,其取决于羯羊输入像素的比例投射一个,两个或四个目的地像素的贡献是正确的目的地像素内,重叠的X边界,一个ÿ边界,或两者。 (A方案将是不错这里,但我没有一个。)

这里的帆布规模VS在1/3规模zombat我像素规模完善的例子。

请注意,图片可能会在浏览器中得到规模,并通过S.O .jpegized .. 然而,我们看到,有更少的噪声尤其是在袋熊后面的草地上,并在其右侧的分支。在皮毛噪声使得它更对比,但看起来他有白发-unlike源图像 - 。 右图是少上口,但明确更好。

下面的代码做像素完美的缩减:

小提琴结果: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
投票

也许男人你可以试试这个,这是我一直在我project.In用这种方式,你不仅能获得高质量的图像,但你的画布上的任何其他元素。

/* 
 * @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);
}

0
投票

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

您可能会发现3层不同的方法来做到这一点调整大小,这将有助于你理解这些代码是如何工作的,以及为什么。

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

你可能想在你的代码中使用这两个演示完整的代码,并打字稿方法,可以在GitHub的项目中找到。

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

0
投票

代替.85如果我们增加1.0。你会得到确切的答案。

data=canvas.toDataURL('image/jpeg', 1.0);

你可以得到清晰明亮的图像。请检查


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

47
投票

快速帆布重采样以优良的品质: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);
}

28
投票

Suggestion 1 - extend the process pipe-line

您可以使用降压,因为我在你指的是链接中,但你出现在一个错误的方式来使用它们。

下台缩放图像以比上述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

这取决于你想要多少磨砺添加到混合物中,你可以从默认的“模糊”,以非常尖锐的结果:

Suggestion 2 - low level algorithm implementation

如果你想获得最好的结果质量明智的,你需要去低级别,并考虑实施例如这个全新的算法来做到这一点。

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

有没有这种算法的JavaScript的据我所知的实现在这个时候让你在寻找一款手满,如果你想在这个任务交给你扔。

其实质是(从纸摘录):

抽象

内插方向自适应下采样算法,提出了在本文的低比特率图像的编码。给定的图像,该算法能够获得低分辨率图像,从与相同的分辨率输入图像的高质量的图像可以被内插。从传统的下采样算法,其是独立于内插处理的不同,所提出的下采样算法铰链下采样到内插处理。因此,所提出下采样算法是能够保持所述输入图像的最大程度的原始信息。然后,将下采样的图像被馈送到JPEG。然后,总变化(TV)基于后处理被施加到解压缩的低分辨率图像。最终,处理后的图像进行插值,以保持所述输入图像的原始分辨率。实验结果验证由该算法利用下采样图像,具有高得多的质量的内插图像,可以实现。此外,该算法能够实现比JPEG的低比特率编码的图像性能优越。

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


20
投票

如果您希望只用帆布,最好的结果将是与多个downsteps。但是,这并不是好enougth呢。为了获得更好的质量,你需要纯JS实现。我们刚刚发布pica - 高速downscaler可变质量/速度。总之,它调整大小1280×1,024像素x在0.1秒〜,并在1秒5000 * 3000px图像,用最高的质量(Lanczos法用3个裂片筛选)。皮卡具有demo,在这里您可以与您的图像,质量水平发挥,甚至尝试在移动设备上。

异食癖没有USM锐化还,但将很快增加。这比实现高速卷积过滤器大小调整更加容易。


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

8
投票

没有人谁真正需要调整图像本身,而只是缩小文件大小正确的答案。

我曾与“直接从摄像机”的照片的问题,我的客户经常在“解压缩” JPEG上传。

事实并非如此众所周知的是,在画布上的支持(在大多数浏览器2017年)改JPEG质量

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

有了这一招,我可以减少一个4K x 3K图片与> 10MB增加到1或2MB,确保它取决于你的需要。

look here


4
投票

这里是高品质的图像/调整大小的画布可重用的角度服务:https://gist.github.com/fisch0920/37bac5e741eaec60e983

该服务支持兰克泽斯卷积和逐步缩小。卷积方法是在被较慢的成本更高的质量,而逐步缩减方法产生合理抗锯齿结果和是显著更快。

实例:

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
    })
})

4
投票

这是改进埃尔米特调整滤波器,利用1名工人,使窗口不冻结。

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


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] );
© www.soinside.com 2019 - 2024. All rights reserved.