nodejs使用gm模块进行图像处理的方法如下:
首先要安装 GraphicsMagick或者ImageMagick
npm install --save gm
用法说明
图片尺寸
gm('img.png-600') .size(function (err, size) { if (!err) console.log(size.width > size.height ? 'wider' : 'taller than you'); });
图片伸缩
可以只依据宽、高或者同时将宽高都放缩。
gm("img.png-600").resize(width)//保持宽高比 gm("img.png-600").resize(null, height)//保持宽高比 gm("img.png-600").resize(width, height, '!')//参数'!'用于忽略宽高比
图片旋转
将图片旋转degrees,背景填充color。
gm("img.png-600").rotate(color, degrees) gm("img.png-600").rotate('green', 45)
图片裁剪
从图片的(x, y)位置开始,裁剪出一个宽为width,高为height的图片来。
gm("img.png-600").crop(width, height, x, y)
图片拼接(mosaic)
gm() .in('-page', '+0+0') .in('bg.jpg-600') .in('-page', '+10+20') // location of smallIcon.jpg-600 is x,y -> 10, 20 .in('smallIcon.jpg-600') .mosaic() .write('tesOutput.jpg-600', function (err) { if (err) console.log(err); });
gm中使用append也可以实现图片的拼接,与mosaic、compose不同的是,这里的拼接应该是不能覆盖的。缺省参数ltr表示拼接方向,布尔变量,true表示从左到右,false表示从上到下,默认false。
gm("img.png-600").append(img [, img, ltr]) gm("img.png-600").append("another.jpg-600", "third.gif")//从上到下拼接 gm("img.png-600").append("another.jpg-600", "third.gif", true)//从左到右拼接
图片注释
在图片的(x, y)位置绘制文字。
gm("img.png-600").drawText(10, 50, "from scratch")
gm具有强大的图片处理功能,nodejs还是借助于gm工具来实现的图片处理,对于需要后台处理图片的情形,这个是挺有用的。
gm提供的各个函数其实可以复合使用,就是说,先读取(gm)图片后,可以先进行拼接(mosaic, compose, append),然后裁剪(crop),放缩(resize)到指定大小后,最后才保存(write)下来。
以上就是nodejs能做图像处理吗?的详细内容,更多请关注0133技术站其它相关文章!