乐趣区

关于javascript:canvas自动裁剪图片空白区域

<!DOCTYPE html>
<html>
<head>

<title>canvas 主动裁剪图片空白区域 </title>

</head>
<body>

<input type="file" id="imageInput" accept="image/*">
<canvas id="canvas" style="display:none;"></canvas>
<div style="margin: 20px 0">
    <img id="outputImage" src=""alt=" 剪切后的图片 ">
</div>
<script>
    const imageInput = document.getElementById('imageInput');
    const canvas = document.getElementById('canvas');
    const outputImage = document.getElementById('outputImage');
    const ctx = canvas.getContext('2d');
    imageInput.addEventListener('change', function (e) {const file = e.target.files[0];
        const reader = new FileReader();
        reader.onload = function (event) {const img = new Image();
            img.src = event.target.result;
            img.onload = function () {
                canvas.width = img.width;
                canvas.height = img.height;
                ctx.drawImage(img, 0, 0);
                // 获取图像的像素数据
                const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                const data = imageData.data;
                // 找到非红色像素的边界
                let minX = canvas.width;
                let minY = canvas.height;
                let maxX = -1;
                let maxY = -1;
                for (let y = 0; y < canvas.height; y++) {for (let x = 0; x < canvas.width; x++) {const index = (y * canvas.width + x) * 4; // 每个像素有 4 个通道(RGBA)const red = data[index];
                        const green = data[index + 1];
                        const blue = data[index + 2];
                        // 判断像素是否为红色 (255, 255, 255)
                        if (red === 255 && green === 255 && blue === 255) {// 此像素是红色,跳过} else {
                            // 非红色像素
                            minX = Math.min(minX, x);
                            minY = Math.min(minY, y);
                            maxX = Math.max(maxX, x);
                            maxY = Math.max(maxY, y);
                        }
                    }
                }
                // 计算剪切后的图像宽度和高度
                const croppedWidth = maxX - minX + 1;
                const croppedHeight = maxY - minY + 1;
                // 创立一个新的 Canvas,将非红色区域绘制到新 Canvas 上
                const newCanvas = document.createElement('canvas');
                const newCtx = newCanvas.getContext('2d');
                newCanvas.width = croppedWidth;
                newCanvas.height = croppedHeight;
                newCtx.drawImage(canvas, minX, minY, croppedWidth, croppedHeight, 0, 0, croppedWidth, croppedHeight);
                // 将解决后的图像显示在页面上的 <img> 元素中
                outputImage.src = newCanvas.toDataURL();};
        };
        reader.readAsDataURL(file);
    });
</script>

</body>
</html>

退出移动版