记录:nodejs 裁切图片的方法

1、jimp github文档

1、读取本地图片切图

jimp.read('本地图片地址', function (err, img) {
    if (err) throw err
    img
  	  .crop(x坐标起点, y坐标起点, width最终图片宽度, height最终图片高度)
      .write(result)
})

2、读取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)
})
2、graphicsMagick、imageMagick GM

1、需要下载工具graphicsMagick | imageMagick并配置环境变量
2、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')
    }
  })
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值