介绍
一个可将图片自动分段裁剪成多张图片的工具。
举个栗子
在线地址
Github站点:https://hu243285237.github.io/PictureCutter_Web/
国内站点: http://hu243285237.gitee.io/picturecutter_web
项目地址
https://hu243285237.github.io/PictureCutter_Web/
兼容性
请在 PC 端使用 Chrome、Firefox、Edge 等浏览器,不支持 IE 浏览器。
原理
主要使用了 Canvas Context 的 drawImage 方法,对图片进行分段绘制。
图片选取、分段绘制和导出都在本地浏览器执行,无额外请求资源消耗。
主要代码
/**
* 以像素裁剪图片
* @param imgURL 图片
* @param pixelWidth 像素宽度
* @param pixelHeight 像素高度
* @param format 裁剪后的图片格式
* @returns 裁剪后的图片数组
*/
export function pixelCut(
imgURL: string,
pixelWidth: number,
pixelHeight: number,
format: string
): Array<string> {
const res = new Array<string>();
const img = new Image();
img.src = imgURL;
const amountRow = Math.ceil(img.width / pixelWidth);
const amountCol = Math.ceil(img.height / pixelHeight);
for (let i = 0; i < amountCol; i++) {
for (let j = 0; j < amountRow; j++) {
const canvas = document.createElement('canvas');
[canvas.width, canvas.height] = [pixelWidth, pixelHeight];
const context = canvas.getContext('2d');
context?.drawImage(
img,
pixelWidth * j,
pixelHeight * i,
pixelWidth,
pixelHeight,
0,
0,
pixelWidth,
pixelHeight
);
res.push(canvas.toDataURL('image/' + format, 1.0));
}
}
return res;
}
/**
* 以数量均等裁剪
* @param imgURL 图片
* @param amountRow 横向切割成几份
* @param amountCol 纵向切割成几份
* @param format 裁剪后的图片格式
* @returns 裁剪后的图片数组
*/
export function amountCut(
imgURL: string,
amountRow: number,
amountCol: number,
format: string
): Array<string> {
const res = new Array<string>();
const img = new Image();
img.src = imgURL;
const pixelWidth = img.width / amountRow;
const pixelHeight = img.height / amountCol;
for (let i = 0; i < amountCol; i++) {
for (let j = 0; j < amountRow; j++) {
const canvas = document.createElement('canvas');
[canvas.width, canvas.height] = [pixelWidth, pixelHeight];
const context = canvas.getContext('2d');
context?.drawImage(
img,
pixelWidth * j,
pixelHeight * i,
pixelWidth,
pixelHeight,
0,
0,
pixelWidth,
pixelHeight
);
res.push(canvas.toDataURL('image/' + format, 1.0));
}
}
return res;
}