首页 > 解决方案 > 从坐标存储在缓冲区中的Javascript裁剪图像

问题描述

我找到了使用画布在 javascript 中裁剪图像的代码,但我需要裁剪一个从未实际显示在任何地方的图像,因为我只需要从图像中获取数据。有一个屏幕截图,然后需要从特定坐标裁剪缓冲的屏幕截图图像。

图像只是存储在一个以 开头的变量中let img = new Image()。如何修改此代码以裁剪仅存储在缓冲区中的图像?

function resizeImage(url, width, height, x, y, callback) {
    var canvas = document.createElement("canvas");
    var context = canvas.getContext('2d');
    var imageObj = new Image();

    // set canvas dimensions

    canvas.width = width;
    canvas.height = height;

    imageObj.onload = function () {
        context.drawImage(imageObj, x, y, width, height, 0, 0, width, height);
        callback(canvas.toDataURL());
    };

    imageObj.src = url;
}

标签: javascriptcrop

解决方案


由于没有人回答,我将发布我发现的内容。最后,我使用库 Sharp 的提取功能实现了我所需要的。

img.onload = resizeImg;
img.src = 'image.png';

function resizeImg() {
  this.path = this.path = 'image.png';

  sharp(this.path)
  .resize(this.width * 2, this.height * 2)
  .extract({ width: 100, height: 20, left: 250, top: 100 })
  .toBuffer({ resolveWithObject: true })
  .then(({ data, info }) => {
      //process data
  })
}

推荐阅读