javascript - 根据javascript中的空白裁剪图像
问题描述
我正在开发一个 Javascript 项目,但我有点卡住了。我想制作一个将图像作为参数的函数,并返回相同的图像但裁剪了空格。这是一个例子:
前
后
我尝试了在堆栈上找到的这个函数:
function removeImageBlanks(imageObject) {
imgWidth = imageObject.width;
imgHeight = imageObject.height;
var canvas = document.createElement('canvas');
canvas.setAttribute("width", imgWidth);
canvas.setAttribute("height", imgHeight);
var context = canvas.getContext('2d');
context.drawImage(imageObject, 0, 0);
var imageData = context.getImageData(0, 0, imgWidth, imgHeight),
data = imageData.data,
getRBG = function(x, y) {
var offset = imgWidth * y + x;
return {
red: data[offset * 4],
green: data[offset * 4 + 1],
blue: data[offset * 4 + 2],
opacity: data[offset * 4 + 3]
};
},
isWhite = function (rgb) {
// many images contain noise, as the white is not a pure #fff white
return rgb.red > 200 && rgb.green > 200 && rgb.blue > 200;
},
scanY = function (fromTop) {
var offset = fromTop ? 1 : -1;
// loop through each row
for(var y = fromTop ? 0 : imgHeight - 1; fromTop ? (y < imgHeight) : (y > -1); y += offset) {
// loop through each column
for(var x = 0; x < imgWidth; x++) {
var rgb = getRBG(x, y);
if (!isWhite(rgb)) {
if (fromTop) {
return y;
} else {
return Math.min(y + 1, imgHeight);
}
}
}
}
return null; // all image is white
},
scanX = function (fromLeft) {
var offset = fromLeft? 1 : -1;
// loop through each column
for(var x = fromLeft ? 0 : imgWidth - 1; fromLeft ? (x < imgWidth) : (x > -1); x += offset) {
// loop through each row
for(var y = 0; y < imgHeight; y++) {
var rgb = getRBG(x, y);
if (!isWhite(rgb)) {
if (fromLeft) {
return x;
} else {
return Math.min(x + 1, imgWidth);
}
}
}
}
return null; // all image is white
};
var cropTop = scanY(true),
cropBottom = scanY(false),
cropLeft = scanX(true),
cropRight = scanX(false),
cropWidth = cropRight - cropLeft,
cropHeight = cropBottom - cropTop;
canvas.setAttribute("width", cropWidth);
canvas.setAttribute("height", cropHeight);
// finally crop the guy
canvas.getContext("2d").drawImage(imageObject,
cropLeft, cropTop, cropWidth, cropHeight,
0, 0, cropWidth, cropHeight);
return canvas.toDataURL();
}
但我仍然遇到错误:
index.js:63 Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
at removeImageBlanks (http://127.0.0.1:5500/index.js:63:29)
at <anonymous>:1:1
我已经尝试添加 img.crossOrigin = 'Anonymous'; 但它仍然不起作用。
解决方案
推荐阅读
- java - java中如何查询权威dns服务器即时获取txt记录
- php - 如何根据每个性别的选定计数获取行?
- elasticsearch - 在 Elasticsearch 中突出显示嵌套对象
- typescript - 使用条件 rxjs6 重构嵌套订阅
- clang-tidy - 如何使用带有 -Wdocumentation 标志的 clang-tidy
- android - Retrofit2 和 DBFlow 读取保存和实体详细信息
- javascript - 仅允许在材质 ui 中达到一定长度的数字
- python - 使用 python 脚本读取未读邮件
- java - 如何在 Android 中使用计时器
- spring-boot - 请求被拒绝,因为在 Docushare Flex 中创建新文档时未找到多部分边界