设计出图后经常需要改下尺寸放在别的项目上使用,每次都是设计手工处理,其实图片服务可以做更多事情,比如借助强大的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做响应图片的更多相关文章

  1. csharp通过dll调用opencv函数,图片作为参数

    [blog 项目实战派]csharp通过dll调用opencv函数,图片作为参数          ​一直想做着方面的研究,但是因为这个方面的知识过于小众,也是由于自己找资料的能力比较弱,知道今天才找 ...

  2. 如何在程序中调用Caffe做图像分类

    Caffe是目前深度学习比较优秀好用的一个开源库,采样c++和CUDA实现,具有速度快,模型定义方便等优点.学习了几天过后,发现也有一个不方便的地方,就是在我的程序中调用Caffe做图像分类没有直接的 ...

  3. IOS5开发-http get/post调用mvc4 webapi互操作(图片上传)[转]

    IOS5开发-http get/post调用mvc4 webapi互操作(图片上传)   目前最流行的跨平台交互是采用http协议通过JSON对象进行互操作.这种方式最简单,也很高效.webservi ...

  4. 使用js做创建图片及删除图片 若有什么不对或不完整的地方,请大家提出来,谢谢

    首先我们要在<body>中创建一个按钮<button>来用作点击创建图片,在<button>中写一个点击事件(随便命名), 在创建一个<div>存放图片 ...

  5. 媳妇儿喜欢玩某音中的动漫特效,那我就用python做一个图片转化软件。

    ​    最近某音上的动漫特效特别火,很多人都玩着动漫肖像,我媳妇儿也不例外.看着她这么喜欢这个特效,我决定做一个图片处理工具,这样媳妇儿的动漫头像就有着落了.编码    为了快速实现我们的目标,我们 ...

  6. 采用React + Fabric + ImageMagick 实现大图片DIY定制

    一,需求背景: 某个印刷公司,有一系列的设计文件模板.接到客户订单时,就在这些设计文件模板上,做一些简单的定制,就能够满足客户的印刷需求. 如在设计文件模板上添加客户的Logo,二维码,联系方式等. ...

  7. opencv通过dll调用matlab函数,图片作为参数

    [blog 项目实战派]opencv通过dll调用matlab函数,图片作为参数                   前文介绍了如何“csharp通过dll调用opencv函数,图片作为参数”.而在实 ...

  8. 微信分享功能引入页面-控制分享时候调用的标题、图片、url和微信按钮隐藏显示控制

    1.设置分享调用的标题.图片.url预览. 2.控制右上角三个点按钮的隐藏显示(和底部工具栏的显示隐藏--未测试). 3.判断网页是否在微信中被调用. <!doctype html> &l ...

  9. SVG如何做圆形图片

    SVG如何做圆形图片 2016年5月31日17:30:48 提到圆形图片,大家首先想到的一定是border-radius,但在SVG中这些方法很难起效,下面方法适合SVG中制作任意规则与不规则的图形. ...

随机推荐

  1. SqlServer执行存储过程时,参数值为null,sql语句参数值变成default

    从C#代码里传入参数到调用存储过程,参数的值为null,执行存储过程一直提示需要参数 '@xxx',但未提供该参数.通过profiler发现生成的参数值变成为default. 解决方案:1.将Para ...

  2. B - Letter(最小覆盖矩形)

    Problem description A boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sh ...

  3. JUC集合-BlockingQueue

    BlockingQueue 阻塞队列,支持两个附加操作. 1,在队列为空时,获取元素的线程会等待对列变为非空. 2,在队列为满时,存储元素的线程会等待对列可用. 使用场景: 生产者往对列里添加元素 消 ...

  4. es6学习 http://es6.ruanyifeng.com/

    基础学习   http://es6.ruanyifeng.com/  够了 1字符串 字符串的遍历器接口 for (let codePoint of 'foo') { console.log(code ...

  5. 用户 'NT Service\MSSQLServerOLAPService' 登录失败

    初学SSAS,部署微软官方示例项目AdventureWorksDW2012Multidimensional时出现错误:用户 'NT Service\MSSQLServerOLAPService' 登录 ...

  6. 如何上传SNAPSHOT类型的JAR文件到nexus中

    在要上传的文件的目录中执行以下命令即可: mvn deploy:deploy-file -DgroupId=com.alibaba -DartifactId=dubbo -Dversion=2.5.4 ...

  7. Windows2012R2 时间同步设置

    Windows2012R2里没有了internet时间,或者Internet时间无法同步成功,都可以尝试使用如下方法. 1.打开命令提示符, 输入:gpedit.msc,打开组策略管理器 2.执行上述 ...

  8. TF基础5

    卷积神经网络CNN 卷积神经网络的权值共享的网络结构显著降低了模型的复杂度,减少了权值的数量. 神经网络的基本组成包括输入层.隐藏层和输出层. 卷积神经网络的特点在于隐藏层分为卷积层和池化层. pad ...

  9. python tips:类的动态绑定

    使用实例引用类的属性时,会发生动态绑定.即python会在实例每次引用类属性时,将对应的类属性绑定到实例上. 动态绑定的例子: class A: def test1(self): print(&quo ...

  10. BitmapMesh动画

    一.概要 我们经常用到Canvas.drawBitmap方法,却很少用到Canvas.drawBitmapMesh方法.这个方法为我们做图片变形提供了无限可能,同时也对数学功底有较高的要求.下面先看一 ...