首頁  >  文章  >  web前端  >  ## 如何在 HTML5 Canvas 中實現像素完美的圖像縮小?

## 如何在 HTML5 Canvas 中實現像素完美的圖像縮小?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-26 15:57:30794瀏覽

## How Can I Achieve Pixel-Perfect Image Downscaling in HTML5 Canvas?

HTML5 Canvas 圖像縮小

儘管禁用插值,但在 HTML5 Canvas 中縮小圖像時,您仍然會面臨圖像品質損失。這是因為瀏覽器通常使用簡單的下取樣技術,該技術會引入雜訊和舍入誤差。

像素完美縮小演算法

要獲得最佳質量,請考慮使用像素-完美的降尺度演算法。此演算法可確保原始影像中的每個像素在縮小後的影像中準確表示,無論比例因子為何。

縮小尺寸實現

這是一個JavaScript 實作像素完美縮小演算法:

<code class="javascript">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);

    if (!(scale < 1) || !(scale > 0)) throw ('scale must be a positive number < 1');

    var sqScale = scale * scale;
    var sw = imgCV.width;
    var sh = imgCV.height;
    var tw = Math.floor(sw * scale);
    var th = Math.floor(sh * scale);

    var sBuffer = imgCV.getContext('2d').getImageData(0, 0, sw, sh).data;
    var tBuffer = new Float32Array(3 * tw * th);
    var sx, sy, sIndex, tx, ty, yIndex, tIndex;

    for (sy = 0; sy < sh; sy++) {
        ty = sy * scale;
        yIndex = 3 * ty * tw;

        for (sx = 0; sx < sw; sx++, sIndex += 4) {
            tx = sx * scale;
            tIndex = yIndex + tx * 3;

            var sR = sBuffer[sIndex];
            var sG = sBuffer[sIndex + 1];
            var sB = sBuffer[sIndex + 2];

            tBuffer[tIndex] += sR * sqScale;
            tBuffer[tIndex + 1] += sG * sqScale;
            tBuffer[tIndex + 2] += sB * sqScale;
        }
    }

    // Convert float array into canvas data and draw
    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;

    var pxIndex;

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

    resCtx.putImageData(imgRes, 0, 0);

    return resCV;
}</code>

此演算法可產生高品質的縮小影像,但計算成本較高。如果擔心效能,您可以考慮使用不太準確但更快的下取樣方法,如下所示:

<code class="javascript">function downscaleImageFast(img, scale) {
    var sw = img.width;
    var sh = img.height;
    var tw = Math.floor(sw * scale);
    var th = Math.floor(sh * scale);

    var resCV = document.createElement('canvas');
    resCV.width = tw;
    resCV.height = th;
    var resCtx = resCV.getContext('2d');
    resCtx.drawImage(img, 0, 0, sw, sh, 0, 0, tw, th);

    return resCV;
}</code>

選擇正確的方法

最佳方法縮小圖像尺寸取決於您的特定要求。為了獲得高品質的結果,請使用像素完美演算法。然而,如果效能很關鍵,快速下採樣方法可能是可以接受的。

以上是## 如何在 HTML5 Canvas 中實現像素完美的圖像縮小?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn