调用imagemagick做响应图片
设计出图后经常需要改下尺寸放在别的项目上使用,每次都是设计手工处理,其实图片服务可以做更多事情,比如借助强大的im,可以通过url控制图片尺寸
var childProcess = require('child_process')
var path = require('path')
,http = require('http')
,fs = require('fs')
const dns_host = 'xxx.net' //图片源站地址
const PATH_IMGS = '/home/work/demo/images' //目录存放
const PATH_IMG_TMP = '/home/work/demo/images' //临时目录
//图片尺寸参数
// /pic/_hd/cd/19/d6d821de10662d5352ff2d6bbaf2_960_420.cj.100x100x15.jpg
const REG_RESIZE_OPT = /\.(\d+)?x(\d+[\!\>\<]?)?x(\d+)?\.jpg/
//图片质量 默认85
// /pic/_hd/cd/19/d6d821de10662d5352ff2d6bbaf2_960_420.cj.q100.100x100x15.jpg
const REG_QUALITY_OPT = /\.q(\d+)\.jpg/ //图片质量参数
http.createServer(function(req, res) {
var imgurl = req.url
,cdn_path = imgurl
var options = cdn_path.match(REG_RESIZE_OPT )
var img_suffix = path.extname(cdn_path)
var opt_img = {}
if (options){
opt_img =
{
"width" : options[1] || ''
,"height" : options[2] || ''
,"mode" : options[3] | 0 || 1
,"imgurl" : imgurl
}
cdn_path = cdn_path.replace(REG_RESIZE_OPT, img_suffix)
}
options = cdn_path.match(REG_QUALITY_OPT)
if (options) {
opt_img.quality = options[1] | 0
cdn_path = cdn_path.replace(REG_QUALITY_OPT, img_suffix)
}
opt_img.quality = opt_img.quality || 85
if (opt_img.quality >= 100) delete opt_img.quality
http.get('http://' + dns_host + cdn_path , function(response){
//因为图片size变了 去掉content-length
delete response.headers['content-length']
res.writeHead(response.statusCode , response.headers)
if (200 !== response.statusCode) return response.pipe(res)
var file_tmp = path.resolve(PATH_IMG_TMP , 'tmp_' + (+new Date).toString(24) + (img_suffix || ''))
//抓取远程图片 临时存图
var writeStream = fs.createWriteStream(file_tmp)
response.pipe(writeStream)
writeStream.on('error' ,function(err){
console.log('err' , err)
res.end(err.toString())
})
response.on('end' ,function(err){
imgWorker(file_tmp , opt_img , (err ,imgsrc) => {
if (err) return res.end(err.toString())
imgsrc = imgsrc || file_tmp
var read_stream = fs.createReadStream(imgsrc)
read_stream.pipe(res)
read_stream.on('end' ,function(){
fs.unlink(file_tmp)
})
})
})
})
}).listen(8791) //web服务端口
function mkdirp(p){
p = path.dirname(p)
if (fs.existsSync(p)) return
p = p.split('/')
var pathnow = ''
p.forEach(function(pi){
pathnow += pi + '/'
if (!fs.existsSync(pathnow) ) fs.mkdirSync(pathnow)
})
}
function imgWorker( file_tmp ,opt ,cbk){
opt = opt || {}
const bindPath = '/usr/local/ImageMagick/bin/'
var bindIdentity = bindPath + 'identify'
/*
* mode 0 等比
* mode 1 剪切
* mode 2 压缩填充
* */
if (!opt.height) opt.mode = 0
convert()
function convert(){
var binConvert = bindPath + 'convert'
var img_save_path = PATH_IMGS + opt.imgurl
mkdirp(img_save_path)
/*
convert -resize 1024 file.jpg newfile.jpg
得到图片宽为1024,高根据原始图片比例计算而来
convert -resize x768 file.jpg newfile.jpg
得到的图片高位768,宽根据原始图片比例计算而来
convert -resize 1024×768! file.jpg newfile.jpg
固定宽高缩放,不考虑原是图宽高的比例,把图片缩放到指定大小。
convert -resize “1024×768>” file.jpg newfile.jpg
只有当src.jpg的宽大于1024或高大于768时候,才进行缩小处理,否则生成newfile.jpg和file.jpg具有一样的尺寸。
convert -resize “1024×768<” file.jpg newfile.jpg
只有当src.jpg的宽小于1024或高小于768时候,才进行放大处理,否则生成newfile.jpg和file.jpg具有一样的尺寸。
http://www.imagemagick.org/discourse-server/viewtopic.php?t=18545
*/
var childArgs = []
/*
* NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast
* NorthWest是左上角对齐 ,SouthEast是右下角对齐
* 通过resize参数第二位可以控制对应对齐方式 默认Center 居中
*/
if (opt.mode) {
var _m = opt.mode.toString()
var gravity = ['NorthWest', 'North', 'NorthEast', 'West'
, 'Center', 'East', 'SouthWest', 'South', 'SouthEast']
[(_m.slice(1,2) || 4) | 0]
var color = ['' ,'white' ,'black'][(_m.slice(2,3) || 0) | 0]
opt.mode = _m.slice(0,1) | 0
}
switch (opt.mode){
case 2:
/*
* mode为2x 图片压缩填入指定尺寸 底色填充
* you can resize to the larger dimension and then pad the image
* convert image -resize "275x275" -gravity center -background white -extent 275x275 resultimage
*/
childArgs.push('-resize')
childArgs.push(opt.width + 'x' + opt.height )
childArgs.push('-gravity')
childArgs.push(gravity)
if (color) {
childArgs.push('-background')
childArgs.push(color)
}
childArgs.push('-extent')
childArgs.push( opt.width + 'x' + opt.height )
break
case 1:
/*
* mode为1x 图片拉伸 溢出剪切
*/
var cut = '+0+0'
childArgs.push('-resize')
childArgs.push(opt.width + 'x' + opt.height + '^')
childArgs.push('-gravity')
childArgs.push(gravity)
childArgs.push('-crop')
childArgs.push( opt.width + 'x' + opt.height + cut )
break
default:
/*
* 原图等比例缩放 比例不符合时以原图为准
*/
var opt_size = opt.width || ''
if (opt.height) opt_size += 'x' + opt.height
if (opt_size){
childArgs.push('-resize')
childArgs.push(opt_size)
}
}
//去除元数据 相机信息 ps信息等
childArgs.push('+profile')
childArgs.push('"*"')
childArgs.push('-strip')
if (opt.quality){
childArgs.push('-quality')
childArgs.push(opt.quality)
}
childArgs.push(file_tmp)
childArgs.push(img_save_path)
console.log(childArgs)
childProcess.execFile(binConvert, childArgs, function(err, stdout, stderr) {
err && console.log(err)
cbk(err , img_save_path)
})
}
}
node前端是nginx 对处理过的图片就可以直接使用了
server {
listen 80;
server_name xxx.com;
location /favicon.ico {
return 418;
}
location / {
root /home/work/demo/images ;
try_files $uri $uri/ @router;
}
location @router {
proxy_pass http://127.0.0.1:8791;
}
}
调用imagemagick做响应图片的更多相关文章
- csharp通过dll调用opencv函数,图片作为参数
[blog 项目实战派]csharp通过dll调用opencv函数,图片作为参数 一直想做着方面的研究,但是因为这个方面的知识过于小众,也是由于自己找资料的能力比较弱,知道今天才找 ...
- 如何在程序中调用Caffe做图像分类
Caffe是目前深度学习比较优秀好用的一个开源库,采样c++和CUDA实现,具有速度快,模型定义方便等优点.学习了几天过后,发现也有一个不方便的地方,就是在我的程序中调用Caffe做图像分类没有直接的 ...
- IOS5开发-http get/post调用mvc4 webapi互操作(图片上传)[转]
IOS5开发-http get/post调用mvc4 webapi互操作(图片上传) 目前最流行的跨平台交互是采用http协议通过JSON对象进行互操作.这种方式最简单,也很高效.webservi ...
- 使用js做创建图片及删除图片 若有什么不对或不完整的地方,请大家提出来,谢谢
首先我们要在<body>中创建一个按钮<button>来用作点击创建图片,在<button>中写一个点击事件(随便命名), 在创建一个<div>存放图片 ...
- 媳妇儿喜欢玩某音中的动漫特效,那我就用python做一个图片转化软件。
最近某音上的动漫特效特别火,很多人都玩着动漫肖像,我媳妇儿也不例外.看着她这么喜欢这个特效,我决定做一个图片处理工具,这样媳妇儿的动漫头像就有着落了.编码 为了快速实现我们的目标,我们 ...
- 采用React + Fabric + ImageMagick 实现大图片DIY定制
一,需求背景: 某个印刷公司,有一系列的设计文件模板.接到客户订单时,就在这些设计文件模板上,做一些简单的定制,就能够满足客户的印刷需求. 如在设计文件模板上添加客户的Logo,二维码,联系方式等. ...
- opencv通过dll调用matlab函数,图片作为参数
[blog 项目实战派]opencv通过dll调用matlab函数,图片作为参数 前文介绍了如何“csharp通过dll调用opencv函数,图片作为参数”.而在实 ...
- 微信分享功能引入页面-控制分享时候调用的标题、图片、url和微信按钮隐藏显示控制
1.设置分享调用的标题.图片.url预览. 2.控制右上角三个点按钮的隐藏显示(和底部工具栏的显示隐藏--未测试). 3.判断网页是否在微信中被调用. <!doctype html> &l ...
- SVG如何做圆形图片
SVG如何做圆形图片 2016年5月31日17:30:48 提到圆形图片,大家首先想到的一定是border-radius,但在SVG中这些方法很难起效,下面方法适合SVG中制作任意规则与不规则的图形. ...
随机推荐
- Tomcat容器的Session管理
Session管理是JavaEE容器比较重要的一部分,在app中也经常会用到.在开发app时,我们只是获取一个session,然后向session中存取数据,然后再销毁session.那么如何产生se ...
- 让Kafka在scala里面跑起来
Kafka集群对消息的保存是根据Topic进行归类的,由消息生产者(Producer)和消息消费者(Consumer)组成,另外,每一个Server称为一个Broker(经纪人).对于Kafka集群而 ...
- Firebird Character Sets and Collations
Firebird Character Sets and Collations Every CHAR or VARCHAR field can (or, better: must) have a cha ...
- DP:***24种设计模式--转自刘伟
转自于高人的文章:http://blog.csdn.net/lovelion/article/details/17517213 2012年-2013年,Sunny在CSDN技术博客中陆续发表了100多 ...
- Jquery中拿到相同的对应的所有的标签
在Jquery中相同的ID号不能用$()获得,即使是$().each()也不能获得所有的ID相同的元素,只能获得第一个匹配的元素. 比如: 以上4个div,如果用$("#jevoly&quo ...
- JsonNetResult
public class JsonNetResult : JsonResult { public JsonNetResult() { Settings = new JsonSerializerSett ...
- jmeter图片的上传
首先添加一个线程组,然后在线程组里面添加一个http请求,因为是发送数据,所有是post请求,写好上传的地址,然后写好文件路径 1.添加线程组 :右键测试计划,添加-Threads(Users)-线程 ...
- Python笔记22-----高阶函数
1.sorted(排序对象,key=):排序对象可以是类别,也可以是字符串和字典,key为自定义排序,如:[key=abs,按绝对值排序][key=lambda x:x[1],按排序对象的第二个值排序 ...
- input标签处理多文件上传
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name ...
- 利用vue-gird-layout 制作可定制桌面 (二)
添加资源池 根据项目需求 添加, 实例两个数据 { "mainData": [ { "x": 0, "y": 0, "w" ...