JavaScript 像素图片放大不失真,以及各种算法模拟放缩图片效果,

 测试代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        li {
            list-style-type: none;
        }

        .one {
            background-repeat: no-repeat;
            background-size: cover;
        }

        .result {
            width: 100%;
            border: 4px aqua solid;
            border-radius: 14px;
            text-align: center;
        }

        .result ul {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-evenly;
            align-content: space-evenly;
        }

        .result ul li {
            position: relative;
            border: 6px aquamarine solid;
            border-radius: 12px;
            margin-right: 10px;
            margin-bottom: 10px;
            padding-top: 30px;
        }

        .result ul li .title {
            position: absolute;
            top: 0;
            left: 0;
            color: purple;
            font-weight: bold;

        }

        .result ul li .DownLoadbtn {
            position: absolute;
            bottom: 0;
            left: 50%;
            font-size: 20px;
            transform: translateX(-50%);
            color: rgb(255, 0, 162);
            font-weight: bold;
        }
    </style>
</head>

<body>
    <button onclick="openImage()">点击选择图片</button>
    <input type="file" id="imageInput" style="display:none;">
    <br><br>
    <div style="border: 4px greenyellow solid;border-radius: 10px;">

        <span style="vertical-align: top;">原始图像:</span>
        <canvas id="show" width="0" height="0"></canvas>
    </div>
    <br>
    <span>倍率:</span>
    <input type="text" id="rateInput">
    <button onclick="GetResult()">渲染</button>
    <br><br>
    <div class="result">
        <h1>不同算法渲染结果:</h1>
        <ul>
        </ul>
    </div>
    <script>
        const in1 = document.querySelector('#rateInput');
        const orginPic = new Image();
        const orginCanvas = document.querySelector('#show');
        const originalCtx = orginCanvas.getContext('2d', { willReadFrequently: true });
        const ul = document.querySelector('ul');
        let rate = 1;//放缩倍率;
        let w;//盒子宽度;
        let h;//盒子高度; 
        let originalImageData; // 获取原始图像的像素数据
        orginPic.onload = () => {
            orginCanvas.width = orginPic.width;
            orginCanvas.height = orginPic.height;
            originalCtx.drawImage(orginPic, 0, 0, orginCanvas.width, orginCanvas.height);
            // 获取原始图像的像素数据
            originalImageData = originalCtx.getImageData(0, 0, orginPic.width, orginPic.height);

        }
        function CheckIsEqual(one, two) {//特异性检测;
            let length = one.data.length;
            for (let i = 0; i < length; i++) {
                if (one.data[i] != two.data[i]) return false;
            }
            return true;
        }
        function GetResult() {//渲染按钮点击执行;
            if (orginPic.src == '') {
                alert("请先选择一张图片");
                return;
            }
            ul.innerHTML = '';
            rate = +in1.value;
            w = rate * orginPic.width;
            h = rate * orginPic.height;

            //dataMes是为了测试用的,没什么用;
            let dataMes1 = Draw();
            let dataMes2 = NearestNeighbor();
            let dataMes3 = Bilinear();
            let dataMes6 = BicubicInterpolation();
            let dataMes7 = SupersamplingAntiAliasing();

        }

        function createBtn(canvas, str) {
            const btn = document.createElement('button');
            btn.innerHTML = '下载'
            btn.classList.add('DownLoadbtn');
            btn.addEventListener('click', function () {
                canvas.toBlob((blob) => {
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `${str}.png`;
                    a.click();
                    URL.revokeObjectURL(url);
                }, 'image/png');

            })
            return btn;
        }
        function openImage() {//从文件中打开图片;
            document.getElementById('imageInput').click();
            document.getElementById('imageInput').addEventListener('change', function () {
                const file = this.files[0];
                if (file && (file.type.startsWith('image/'))) {
                    const reader = new FileReader();
                    reader.onloadend = function () {
                        orginPic.src = reader.result;
                    };
                    if (file) {
                        reader.readAsDataURL(file);
                    }
                }
            });
        }
        function createLi(str) {
            let li = document.createElement('li');
            li.innerHTML = `<div class="title">${str}</div>`
            ul.append(li);
            li.style.width = w + 'px';
            li.style.height = h + 40 + 'px';



            return li;

        }
        function Draw() {
            let li = createLi('canvas: ')
            const canvas = document.createElement('canvas');
            li.appendChild(canvas);
            canvas.width = w;
            canvas.height = h;
            const rtx = canvas.getContext('2d');
            rtx.drawImage(orginPic, 0, 0, w, h);
            li.appendChild(createBtn(canvas, 'canvasDrawImg'));
            return rtx.getImageData(0, 0, w, h);
        }
        function NearestNeighbor() {
            let li = createLi('NearestNeighbor: ')
            const canvas = document.createElement('canvas');
            li.appendChild(canvas);
            canvas.width = w;
            canvas.height = h;
            const rtx = canvas.getContext('2d');

            // 调用最近邻插值缩放函数
            const scaledImageData = nearestNeighborScale(originalImageData, w, h);

            // 将缩放后的像素数据绘制到缩放后画布上
            rtx.putImageData(scaledImageData, 0, 0);
            li.appendChild(createBtn(canvas, 'NearestNeighborDrawImg'));
            return rtx.getImageData(0, 0, w, h);
        }
        function Bilinear() {
            let li = createLi('Bilinear: ')
            const canvas = document.createElement('canvas');
            li.appendChild(canvas);
            canvas.width = w;
            canvas.height = h;
            const rtx = canvas.getContext('2d');

            // 调用双线性插值缩放函数
            const scaledImageData = bilinearScale(originalImageData, w, h);

            // 将缩放后的像素数据绘制到缩放后画布上
            rtx.putImageData(scaledImageData, 0, 0);
            li.appendChild(createBtn(canvas, 'BilinearDrawImg'));

            return rtx.getImageData(0, 0, w, h);

        }
        function BicubicInterpolation() {
            let li = createLi('Bicubic-Interpolation: ')
            const canvas = document.createElement('canvas');
            li.appendChild(canvas);
            canvas.width = w;
            canvas.height = h;
            const rtx = canvas.getContext('2d');

            // BicubicInterpolation
            const scaledImageData = bicubicScale(originalImageData, w, h);

            // 将缩放后的像素数据绘制到缩放后画布上
            rtx.putImageData(scaledImageData, 0, 0);
            li.appendChild(createBtn(canvas, 'BicubicDrawImg'));

            return rtx.getImageData(0, 0, w, h);
        }
        function SupersamplingAntiAliasing() {
            let li = createLi('SSAA: ')
            const canvas = document.createElement('canvas');
            li.appendChild(canvas);
            canvas.width = w;
            canvas.height = h;
            const rtx = canvas.getContext('2d');

            // 定义超采样倍数
            const supersampleFactor = 2;
            // 创建高分辨率画布
            const supersampledCanvas = document.createElement('canvas');
            const supersampledCtx = supersampledCanvas.getContext('2d');
            supersampledCanvas.width = w * supersampleFactor;
            supersampledCanvas.height = h * supersampleFactor;

            // 将原始图像绘制到高分辨率画布上
            supersampledCtx.drawImage(orginPic, 0, 0, supersampledCanvas.width, supersampledCanvas.height);

            // 获取高分辨率画布的像素数据
            const supersampledImageData = supersampledCtx.getImageData(0, 0, supersampledCanvas.width, supersampledCanvas.height);

            // 降采样
            const scaledImageData = SSAA(supersampledImageData, w, h, supersampleFactor);

            rtx.putImageData(scaledImageData, 0, 0);
            li.appendChild(createBtn(canvas, 'SSAADrawImg'));

            return rtx.getImageData(0, 0, w, h);
        }

        //#region  最近邻插值缩放函数
        function nearestNeighborScale(imageData, newWidth, newHeight) {
            // 创建一个新的图像数据对象,用于存储缩放后的像素数据
            const newImageData = originalCtx.createImageData(newWidth, newHeight);
            // 计算水平和垂直方向的缩放比例
            const scaleX = imageData.width / newWidth;
            const scaleY = imageData.height / newHeight;

            // 遍历缩放后图像的每个像素
            for (let y = 0; y < newHeight; y++) {
                for (let x = 0; x < newWidth; x++) {
                    // 计算目标像素在原始图像中对应的位置
                    const srcX = Math.floor(x * scaleX);
                    const srcY = Math.floor(y * scaleY);
                    // 计算目标像素在原始图像数据数组中的索引
                    const srcIndex = (srcY * imageData.width + srcX) * 4;
                    // 计算目标像素在新图像数据数组中的索引
                    const destIndex = (y * newWidth + x) * 4;

                    // 将原始图像中对应像素的颜色值复制到新图像数据中
                    newImageData.data[destIndex] = imageData.data[srcIndex];
                    newImageData.data[destIndex + 1] = imageData.data[srcIndex + 1];
                    newImageData.data[destIndex + 2] = imageData.data[srcIndex + 2];
                    newImageData.data[destIndex + 3] = imageData.data[srcIndex + 3];
                }
            }

            return newImageData;
        }
        //#endregion

        //#region  双线性插值缩放函数
        function bilinearScale(imageData, newWidth, newHeight) {
            // 创建一个新的图像数据对象,用于存储缩放后的像素数据
            const newImageData = originalCtx.createImageData(newWidth, newHeight);
            // 计算水平和垂直方向的缩放比例
            const scaleX = imageData.width / newWidth;
            const scaleY = imageData.height / newHeight;

            // 遍历缩放后图像的每个像素
            for (let y = 0; y < newHeight; y++) {
                for (let x = 0; x < newWidth; x++) {
                    // 计算目标像素在原始图像中对应的浮点坐标
                    const srcX = x * scaleX;
                    const srcY = y * scaleY;
                    // 计算四个相邻像素的坐标
                    const x0 = Math.floor(srcX);
                    const y0 = Math.floor(srcY);
                    const x1 = Math.min(x0 + 1, imageData.width - 1);
                    const y1 = Math.min(y0 + 1, imageData.height - 1);

                    // 计算插值因子
                    const dx = srcX - x0;
                    const dy = srcY - y0;

                    // 获取四个相邻像素的颜色值
                    const c00 = getPixelColor(imageData, x0, y0);
                    const c01 = getPixelColor(imageData, x0, y1);
                    const c10 = getPixelColor(imageData, x1, y0);
                    const c11 = getPixelColor(imageData, x1, y1);

                    // 对每个颜色通道进行双线性插值
                    const r = bilinearInterpolation(c00.r, c10.r, c01.r, c11.r, dx, dy);
                    const g = bilinearInterpolation(c00.g, c10.g, c01.g, c11.g, dx, dy);
                    const b = bilinearInterpolation(c00.b, c10.b, c01.b, c11.b, dx, dy);
                    const a = bilinearInterpolation(c00.a, c10.a, c01.a, c11.a, dx, dy);

                    // 计算目标像素在新图像数据数组中的索引
                    const destIndex = (y * newWidth + x) * 4;
                    // 将插值后的颜色值赋值给新图像数据
                    newImageData.data[destIndex] = r;
                    newImageData.data[destIndex + 1] = g;
                    newImageData.data[destIndex + 2] = b;
                    newImageData.data[destIndex + 3] = a;
                }
            }

            return newImageData;
        }

        // 获取指定位置像素的颜色值
        function getPixelColor(imageData, x, y) {
            const index = (y * imageData.width + x) * 4;
            return {
                r: imageData.data[index],
                g: imageData.data[index + 1],
                b: imageData.data[index + 2],
                a: imageData.data[index + 3]
            };
        }

        // 双线性插值计算
        function bilinearInterpolation(c00, c10, c01, c11, dx, dy) {
            const r0 = (1 - dx) * c00 + dx * c10;
            const r1 = (1 - dx) * c01 + dx * c11;
            return (1 - dy) * r0 + dy * r1;
        }
        //#endregion

        //#region 双三次插值
        function bicubicScale(imageData, newWidth, newHeight) {
            const newImageData = originalCtx.createImageData(newWidth, newHeight);
            const scaleX = imageData.width / newWidth;
            const scaleY = imageData.height / newHeight;

            for (let y = 0; y < newHeight; y++) {
                for (let x = 0; x < newWidth; x++) {
                    const srcX = x * scaleX;
                    const srcY = y * scaleY;
                    const r = bicubicInterpolate(imageData, srcX, srcY, 0);
                    const g = bicubicInterpolate(imageData, srcX, srcY, 1);
                    const b = bicubicInterpolate(imageData, srcX, srcY, 2);
                    const a = bicubicInterpolate(imageData, srcX, srcY, 3);

                    const destIndex = (y * newWidth + x) * 4;
                    newImageData.data[destIndex] = r;
                    newImageData.data[destIndex + 1] = g;
                    newImageData.data[destIndex + 2] = b;
                    newImageData.data[destIndex + 3] = a;
                }
            }

            return newImageData;
        }

        function bicubicInterpolate(imageData, x, y, channel) {
            const x0 = Math.floor(x);
            const y0 = Math.floor(y);
            let result = 0;

            for (let j = -1; j <= 2; j++) {
                for (let i = -1; i <= 2; i++) {
                    const px = Math.min(Math.max(x0 + i, 0), imageData.width - 1);
                    const py = Math.min(Math.max(y0 + j, 0), imageData.height - 1);
                    const weightX = cubicInterpolation(x - px);
                    const weightY = cubicInterpolation(y - py);
                    const index = (py * imageData.width + px) * 4 + channel;
                    const value = imageData.data[index];
                    result += value * weightX * weightY;
                }
            }

            return Math.min(255, Math.max(0, Math.round(result)));
        }

        function cubicInterpolation(t) {
            const a = -0.5;
            const absT = Math.abs(t);
            if (absT <= 1) {
                return (a + 2) * Math.pow(absT, 3) - (a + 3) * Math.pow(absT, 2) + 1;
            } else if (absT < 2) {
                return a * Math.pow(absT, 3) - 5 * a * Math.pow(absT, 2) + 8 * a * absT - 4 * a;
            }
            return 0;
        }
        //#endregion

        //#region SSAA算法;
        function SSAA(supersampledImageData, newWidth, newHeight, supersampleFactor) {
            const newImageData = originalCtx.createImageData(newWidth, newHeight);
            const blockSize = supersampleFactor * supersampleFactor;

            for (let y = 0; y < newHeight; y++) {
                for (let x = 0; x < newWidth; x++) {
                    let rSum = 0;
                    let gSum = 0;
                    let bSum = 0;
                    let aSum = 0;

                    for (let j = 0; j < supersampleFactor; j++) {
                        for (let i = 0; i < supersampleFactor; i++) {
                            const srcX = x * supersampleFactor + i;
                            const srcY = y * supersampleFactor + j;
                            const index = (srcY * supersampledImageData.width + srcX) * 4;

                            rSum += supersampledImageData.data[index];
                            gSum += supersampledImageData.data[index + 1];
                            bSum += supersampledImageData.data[index + 2];
                            aSum += supersampledImageData.data[index + 3];
                        }
                    }

                    const destIndex = (y * newWidth + x) * 4;
                    newImageData.data[destIndex] = Math.round(rSum / blockSize);
                    newImageData.data[destIndex + 1] = Math.round(gSum / blockSize);
                    newImageData.data[destIndex + 2] = Math.round(bSum / blockSize);
                    newImageData.data[destIndex + 3] = Math.round(aSum / blockSize);
                }
            }

            return newImageData;
        }
        //#endregion

    </script>
</body>

</script>
</body>

</html>

运行效果如下图所示:

可以明显看到NearestNeighbor算法,对放大像素图,不失真,效果很好;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值