Javascript 从坐标裁剪存储在缓冲区中的图像
Javascript crop image stored in buffer from coordinates
我发现使用 canvas 在 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;
}
既然没有人回答,我就post我找到的。最后,我使用库 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
})
}
我发现使用 canvas 在 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;
}
既然没有人回答,我就post我找到的。最后,我使用库 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
})
}