将图片转为ascii图片输出
110 浏览2025年06月27日作者:longfei_smaile
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multiple Image to ASCII Converter</title>
    <style>
        .ascii-art {
            white-space: pre;
            font-family: monospace;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <input type="file" id="imageInput" multiple>
    <div id="output"></div>

    <script>
        document.getElementById('imageInput').addEventListener('change', function(event) {
            const files = event.target.files;
            Array.from(files).forEach(file => {
                if (file.type.match('image.*')) {
                    const img = new Image();
                    img.onload = function() {
                        const canvas = document.createElement('canvas');
                        const ctx = canvas.getContext('2d');
                        canvas.width = img.width;
                        canvas.height = img.height;
                        ctx.drawImage(img, 0, 0);
                        const asciiArt = imageToAscii(ctx, img.width, img.height);
                        displayAsciiArt(asciiArt);
                    };
                    img.src = URL.createObjectURL(file);
                }
            });
        });

        function imageToAscii(ctx, width, height) {
            const asciiChars = ['@', '#', 'S', '%', '?', '*', '+', ';', ':', ',', '.'];
            let asciiString = '';
            const imageData = ctx.getImageData(0, 0, width, height);
            for (let i = 0; i < imageData.data.length; i += 4) {
                const r = imageData.data[i];
                const g = imageData.data[i + 1];
                const b = imageData.data[i + 2];
                const avg = Math.floor((r + g + b) / 3);
                const charIndex = Math.floor(avg / 25);
                asciiString += asciiChars[charIndex];
                if ((i + 4) % (width * 4) === 0) {
                    asciiString += '\n';
                }
            }
            return asciiString;
        }

        function displayAsciiArt(asciiArt) {
            const outputDiv = document.getElementById('output');
            const asciiContainer = document.createElement('div');
            asciiContainer.className = 'ascii-art';
            asciiContainer.textContent = asciiArt;
            outputDiv.appendChild(asciiContainer);
        }
    </script>
</body>
</html>



最后一次编辑于 2025 年 06 月 27 日
共 4 条评论

相关文章

专题推荐

热门文章

热门问答