传入图片的base64即可。
function clearblankimg(imgData){
var img = new Image(); //创建图片对象
img.src = imgData;
img.onload = function() {
var c = document.createElement('canvas'); //创建处理画布对象
var ctx = c.getContext('2d');
c.width = img.width;
c.height = img.height;
ctx.drawImage(img, 0, 0); //绘制
var imgData = ctx.getImageData(0, 0, c.width, c.height).data; //读取图片数据
var lOffset = c.width,
rOffset = 0,
tOffset = c.height,
bOffset = 0;
for (var i = 0; i < c.width; i++) {
for (var j = 0; j < c.height; j++) {
var pos = (i + c.width * j) * 4
if (imgData[pos] == 255 || imgData[pos + 1] == 255 || imgData[pos + 2] == 255 || imgData[pos + 3] == 255) {
bOffset = Math.max(j, bOffset); // 找到有色彩的最下端
rOffset = Math.max(i, rOffset); // 找到有色彩的最右端
tOffset = Math.min(j, tOffset); // 找到有色彩的最上端
lOffset = Math.min(i, lOffset); // 找到有色彩的最左端
}
}
}
lOffset++;
rOffset++;
tOffset++;
bOffset++;
var x = document.createElement("canvas"); //创建处理后画布对象
x.width = rOffset - lOffset;
x.height = bOffset - tOffset;
var xx = x.getContext("2d");
xx.drawImage(img, lOffset, tOffset, x.width, x.height, 0, 0, x.width, x.height); //绘制
console.log(x.toDataURL()); //得到最终裁剪出来的base64
}
}
去除前:
图片有大量透明区域是没用的,只需要保留下面的有色区域
去除后:
图片透明区域裁剪掉
标签:img,前端,height,画布,width,去除,var,imgData,tOffset From: https://www.cnblogs.com/Hello233/p/17486711.html