在线长图片自动裁剪工具

介绍

一个可将图片自动分段裁剪成多张图片的工具。

举个栗子

在线地址

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;
}

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值