我的想法是从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
我的问题是如何删除给定任何图像的所有空白区域。
编辑:Keith通过添加onload函数解决了图像问题。
答案 0 :(得分:0)
经过一些修补,我发现所有的&#34;白色&#34;像素不完全是白色所以我修改了它搜索所有近白色像素的if语句:if(r >= 250&& g >= 250 && b >= 250){