用Base64和CORS从图像中删除所有空白



我的想法是从URL获取图像,通过CORS代理发送,将其转换为base64,然后从图像中删除空白,然后用透明的背景替换。我设法这样做:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax Image</title>
    <style>
        body {
            background: darkslategrey;
        }
        .text {
            color: white;
        }
    </style>
</head>
<body>
    <!-- Original -->
    <h3 class="text">Original</h3>
    <img src="" id="original">
    <!-- Modified -->
    <h3 class="text">Modified</h3>
    <canvas id="modified"></canvas>
    <script src="../CommonLinkedFiles/jquery3_2_1.js"></script>
    <script>
        var stockSymbol = "extr";
        var logoUrl = "https://storage.googleapis.com/iex/api/logos/" + stockSymbol.toUpperCase() + ".png";
        // Converting URL to Base64 with the use of a proxy
        var getDataUri = function (targetUrl, callback) {
            var xhr = new XMLHttpRequest();
            xhr.onload = function () {
                var reader = new FileReader();
                reader.onloadend = function () {
                    callback(reader.result);
                };
                reader.readAsDataURL(xhr.response);
            };
            var proxyUrl = 'https://cors-anywhere.herokuapp.com/';
            xhr.open('GET', proxyUrl + targetUrl);
            xhr.responseType = 'blob';
            xhr.send();
        };
        // Returns Base 64 of image
        getDataUri(logoUrl, function (base64) {
            console.log('RESULT:', base64);
            //original
            $("#original").attr("src", base64);
            var canvas = document.getElementById("modified"),
                ctx = canvas.getContext("2d"),
                image = document.getElementById("original");
            canvas.height = canvas.width = 128;
            ctx.drawImage(image,0,0);
            var imgd = ctx.getImageData(0, 0, 128, 128),
                pix = imgd.data,
                newColor = {r:0,g:0,b:0, a:0};
            for (var i = 0, n = pix.length; i <n; i += 4) {
                var r = pix[i],
                    g = pix[i+1],
                    b = pix[i+2];
                if(r == 255&& g == 255 && b == 255){
                    // Change the white to the new color.
                    pix[i] = newColor.r;
                    pix[i+1] = newColor.g;
                    pix[i+2] = newColor.b;
                    pix[i+3] = newColor.a;
                }
            }
            ctx.putImageData(imgd, 0, 0);
        });
    </script>
</body>

您可以在这里看到:JSFIDDLE

我的问题是如何删除所有图像的所有空白。

编辑:基思通过添加Onload功能解决了图像。

在修补一些修补后,我发现所有"白色"像素并非完全白色,因此我对IF语句进行了修改,它搜索了所有近乎白色的像素: if(r >= 250&& g >= 250 && b >= 250){

jsfiddle

最新更新