问题:
canvas裁剪的图把整个画布都剪下来了,但只要有元素的部分
// 图像处理
// 把图片的透明部分去掉
export function getImagesRealSize(dataUrl) {
return new Promise((resolve, reject) => {
// 将Base64解码为二进制数据
let binaryString = atob(dataUrl.split(',')[1]); // 去除dataUrl的前部分(例如"data:image/png;base64,")
let len = binaryString.length;
let bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
// 创建Blob对象
let blob = new Blob([bytes], {
type: 'image/png'
});
// 创建Image对象
let img = new Image();
img.onload = function () {
// 创建Canvas并设置尺寸
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
// 将Image绘制到Canvas
ctx.drawImage(img, 0, 0);
// 获取像素数据
let imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
let data = imageData.data;
let hasData = data.some(item => item !== 0); // 检查是否有非透明像素
if (hasData) {
// 确定非透明像素的边界
let left = canvas.width,
right = 0,
top = canvas.height,
bottom = 0;
for (let y = 0; y < canvas.height; y++) {
for (let x = 0; x < canvas.width; x++) {
let index = (y * canvas.width + x) * 4;
if (data[index + 3] !== 0) { // 检查alpha通道
if (x < left) left = x;
if (x > right) right = x;
if (y < top) top = y;
if (y > bottom) bottom = y;
}
}
}
// 裁剪Canvas到非透明区域
canvas.width = right - left + 1;
canvas.height = bottom - top + 1;
ctx.drawImage(img, left, top, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);
// 导出新的Base64图像数据URL
let newBase64 = canvas.toDataURL();
// 获取新的宽和高
let newWidth = canvas.width;
let newHeight = canvas.height;
console.log("🚀 ~ ServersPlugin ~ returnnewPromise ~ newBase64:340", newBase64, newWidth, newHeight)
resolve({
base64: newBase64,
width: newWidth,
height: newHeight
});
// resolve(newBase64);
} else {
// 如果没有非透明像素,返回一个空白图像的Base64
resolve('data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=');
}
};
img.onerror = reject;
img.src = URL.createObjectURL(blob);
});
}