1、安装 jimp
$ npm install --save jimp
2、读取本地图片切图
jimp.read('本地图片地址', function (err, img) {if (err) throw errimg.crop(x坐标起点, y坐标起点, width最终图片宽度, height最终图片高度).write(result)
})
3、读取http图片,转成buffer,切成buffer数据
const options = {headers: {'User-Agent': 'Mozilla/5.0',}
}
http.get(imgUrl, options ,(response) => {let imgData = ''response.setEncoding('binary')response.on('data', (chunk) => {imgData += chunk})response.on('end', () => {const imgBuffer = new Buffer.from(imgData, 'binary')jimp.read(imgBuffer).then((img) => {const topLeftImage = img.clone() // copy jimp对象进行操作const topRightImage = img.clone()const bottomLeftImage = img.clone()const bottomRightImage = img.clone()const topLeft = topLeftImage.crop(64, 64, 256, 256)topLeft.getBuffer('image/jpeg', (_, buf) => {consoel.log(buf)})const topRight = topRightImage.crop(320, 64, 256, 256)topRight.getBuffer('image/jpeg', (_, buf) => {consoel.log(buf)})const bottomLeft = bottomLeftImage.crop(64, 320, 256, 256)bottomLeft.getBuffer('image/jpeg', (_, buf) => {consoel.log(buf)})const bottomRight = bottomRightImage.crop(320, 320, 256, 256)bottomRight.getBuffer('image/jpeg', (_, buf) => {consoel.log(buf)})}).catch(err => {console.error(err)})})
}).on('error', function (err) {console.log('出错!', err)
})
4、graphicsMagick、imageMagick GM
需要下载工具graphicsMagick | imageMagick并配置环境变量
$ npm i gm
/*** 裁剪图片* @param srcImg 待裁剪的图片路径* @param destImg 裁剪后的图片路径* @param width 宽度* @param height 高度* @param x x坐标* @param y y坐标*/
function cropImgHandle(srcImg, destImg, width, height, x, y) {gm(srcImg).crop(width, height, x, y).write(destImg, function (err) {if (err) {return console.log(err)} else {console.log('success')}})
}
到此 Node 裁切图片的方法介绍完成。