这是答案。注意我使用的是 Caman,因此在加载图像时我不会丢失质量,并且由于 caman 非阻塞线程模型,浏览器的线程不会被阻塞。
https://github.com/meltingice/CamanJS
这可能可以在 webworker 中完成,for 循环无论如何都会进行像素迭代。
如果有人有更有效的方法来做到这一点,请提出建议,我将来可能会这样做,但我现在没有时间。
var canvas = document.createElement("canvas");
canvas.height = 200;
canvas.width = 200;
Caman(canvas, "download.png", function () {
var ctx = canvas.getContext("2d");
var oldid = ctx.getImageData(0, 0, 360, 360);
var newCanvas = document.createElement("canvas");
var newContext2d = newCanvas.getContext("2d");
newCanvas.width = 360;
newCanvas.height = 340;
var vnewid = newContext2d.createImageData(360, 360);
var oldArray = Array.from(oldid.data);
console.log(oldArray);
var arrayToInsert = [];
for (var y = 0; y < 360; ++y) {
for (var x = 0; x < 360; ++x) {
if (y > 90 && y < 110) { // this is how we remove a horizontal line worth of 20 pixels in width.
} else {
var index = (y * 360 + x) * 4; // index of the current pixel
arrayToInsert.push(oldArray[index]);
arrayToInsert.push(oldArray[index + 1]);
arrayToInsert.push(oldArray[index + 2]);
arrayToInsert.push(oldArray[index + 3]);
}
}
}
vnewid.data.set(arrayToInsert);
newContext2d.putImageData(vnewid, 0, 0, 0, 0, 360, 340);
var newC = newCanvas.toDataURL();
console.log(newC);
// take this console.log base64 and put it here.
// https://codebeautify.org/base64-to-image-converter
});
这里是html
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="camanjs.js"></script>
</head>
<body>
<img width="200" height="200" id="f1img" src="download.png" />
<div >
<canvas id="myCanvas"></canvas>
</div>
<script src="index.js"></script>
</body>
</html>