详解用node-images 打造简易图片服务器


Posted in Javascript onMay 08, 2017

Edit:2016-5-11 修正了代码里面一些明显的错误,并发布在 ajaxjs 库之中,源码在这里。

Edit:2016-5-24 加入 HEAD 请求,检测图片大小。如果小于 80kb 则无须压缩,返回 302 重定向。

node HEAD 请求

var http = require('http'); 
var url = require('url'); 
var siteUrl = url.parse('http://img1.gtimg.com/view/pics/hv1/42/80/2065/134297067.jpg'); 
 
request = http.request({ 
  method : 'HEAD', 
  port: siteUrl.port || 80, 
  host: siteUrl.host, 
  path : siteUrl.pathname 
}); 
request.on('response', function (response) { 
  response.setEncoding('utf8'); 
  console.log(response.headers['content-length']); 
}); 
request.end();

必须先赞下国人 npm 库作品:node-images(https://github.com/zhangyuanwei/node-images),封装了跨平台的 C++ 逻辑,形成 nodejs API 让我们这些小白愉快地使用。之前用过 GraphicsMagick for nodejs,功能最强大,但包体积也比较大,依赖度高,最近好像还爆出了漏洞事件。node-images 相比 GM,主要是更轻量级,无需安装任何图像处理库。

安装 node-images:

npm install images

npm 包比较大,node_modules 里面有个 node-images.tar.gz 压缩包,下载完之后可以删掉,但剩余也有 11mb。

图片服务器,当前需求是:一个静态服务器,支持返回 jpg/png/gif 即可;支持 HTTP 缓存;支持指定图片分辨率;支持远程图片加载。加载远程图片,可通过设置 maxLength 来限制图片文件大小。

实施过程中,使用 Step.js 参与了异步操作,比较简单。

服务器的相关配置:

// 配置对象。 
var staticFileServer_CONFIG = { 
  'host': '127.0.0.1',      // 服务器地址 
  'port': 3000,        // 端口 
  'site_base': 'C:/project/bigfoot',   // 根目录,虚拟目录的根目录 
  'file_expiry_time': 480,    // 缓存期限 HTTP cache expiry time, minutes 
  'directory_listing': true    // 是否打开 文件 列表 
};

请求例子:

http://localhost:3001/asset/coming_soon.jpg?w=300
http://localhost:3001/asset/coming_soon.jpg?h=150
http://localhost:3001/asset/coming_soon.jpg?w=300&h=150
http://localhost:3001/?url=http://s0.hao123img.com/res/img/logo/logonew.png

完整源码:

const 
  HTTP = require('http'), PATH = require('path'), fs = require('fs'), CRYPTO = require('crypto'), 
  url = require("url"), querystring = require("querystring"), 
  Step = require('./step'), images = require("images"); 
 
// 配置对象。 
var staticFileServer_CONFIG = { 
  'host': '127.0.0.1',      // 服务器地址 
  'port': 3001,            // 端口 
  'site_base': 'C:/project/bigfoot',     // 根目录,虚拟目录的根目录 
  'file_expiry_time': 480,    // 缓存期限 HTTP cache expiry time, minutes 
  'directory_listing': true    // 是否打开 文件 列表 
}; 
 
const server = HTTP.createServer((req, res) => { 
  init(req, res, staticFileServer_CONFIG); 
}); 
 
server.listen(staticFileServer_CONFIG.port, staticFileServer_CONFIG.host, () => { 
  console.log(`Image Server running at http://${staticFileServer_CONFIG.host}:${staticFileServer_CONFIG.port}/`); 
}); 
 
// 当前支持的 文件类型,你可以不断扩充。 
var MIME_TYPES = { 
  '.txt': 'text/plain', 
  '.md': 'text/plain', 
  '': 'text/plain', 
  '.html': 'text/html', 
  '.css': 'text/css', 
  '.js': 'application/javascript', 
  '.json': 'application/json', 
  '.jpg': 'image/jpeg', 
  '.png': 'image/png', 
  '.gif': 'image/gif' 
}; 
 
MIME_TYPES['.htm'] = MIME_TYPES['.html']; 
 
var httpEntity = { 
  contentType: null, 
  data: null, 
  getHeaders: function (EXPIRY_TIME) { 
    // 返回 HTTP Meta 的 Etag。可以了解 md5 加密方法 
    var hash = CRYPTO.createHash('md5'); 
    //hash.update(this.data); 
    //var etag = hash.digest('hex'); 
 
    return { 
      'Content-Type': this.contentType, 
      'Content-Length': this.data.length, 
      //'Cache-Control': 'max-age=' + EXPIRY_TIME, 
      //'ETag': etag 
    }; 
  } 
}; 
 
function init(request, response) { 
  var args = url.parse(request.url).query,     //arg => name=a&id=5  
    params = querystring.parse(args); 
 
  if (params.url) { 
    getRemoteImg(request, response, params); 
  } else { 
    load_local_img(request, response, params); 
  } 
} 
 
// 加载远程图片 
function getRemoteImg(request, response, params) { 
  var imgData = ""; // 字符串 
  var size = 0; 
  var chunks = []; 
 
  Step(function () { 
      HTTP.get(params.url, this); 
    }, 
    function (res) { 
      var maxLength = 10; // 10mb 
      var imgData = ""; 
      if (res.headers['content-length'] > maxLength * 1024 * 1024) { 
        server500(response, new Error('Image too large.')); 
      } else if (!~[200, 304].indexOf(res.statusCode)) { 
        server500(response, new Error('Received an invalid status code.')); 
      } else if (!res.headers['content-type'].match(/image/)) { 
        server500(response, new Error('Not an image.')); 
      } else { 
        // res.setEncoding("binary"); //一定要设置response的编码为binary否则会下载下来的图片打不开 
        res.on("data", function (chunk) { 
          // imgData+=chunk; 
          size += chunk.length; 
          chunks.push(chunk); 
        }); 
 
        res.on("end", this); 
      } 
       
    }, 
    function () {  
      imgData = Buffer.concat(chunks, size); 
     
      var _httpEntity = Object.create(httpEntity); 
      _httpEntity.contentType = MIME_TYPES['.png']; 
      _httpEntity.data = imgData; 
      // console.log('imgData.length:::' + imgData.length) 
      // 缓存过期时限 
      var EXPIRY_TIME = (staticFileServer_CONFIG.file_expiry_time * 60).toString(); 
      response.writeHead(200); 
      response.end(_httpEntity.data); 
    } 
  ); 
   
} 
 
 
// 获取本地图片 
function load_local_img(request, response, params) { 
  if (PATH.extname(request.url) === '') { 
    // connect.directory('C:/project/bigfoot')(request, response, function(){}); 
    // 如果 url 只是 目录 的,则列出目录 
    console.log('如果 url 只是 目录 的,则列出目录'); 
    server500(response, '如果 url 只是 目录 的,则列出目录@todo'); 
  } else { 
    var pathname = require('url').parse(request.url).pathname; 
    // 如果 url 是 目录 + 文件名 的,则返回那个文件 
    var path = staticFileServer_CONFIG.site_base + pathname; 
 
    Step(function () { 
      console.log('请求 url :' + request.url + ', path : ' + pathname); 
      fs.exists(path, this); 
    }, function (path_exists, err) { 
      if (err) { 
        server500(response, '查找文件失败!'); 
        return; 
      } 
      if (path_exists) { 
        fs.readFile(path, this); 
      } else { 
        response.writeHead(404, { 'Content-Type': 'text/plain;charset=utf-8' }); 
        response.end('找不到 ' + path + '\n'); 
      } 
    }, function (err, data) { 
      if (err) { 
        server500(response, '读取文件失败!'); 
        return; 
      } 
      var extName = '.' + path.split('.').pop(); 
      var extName = MIME_TYPES[extName] || 'text/plain'; 
 
      var _httpEntity = Object.create(httpEntity); 
      _httpEntity.contentType = extName; 
      var buData = new Buffer(data); 
      //images(buData).height(100); 
 
      var newImage; 
 
      if (params.w && params.h) { 
        newImage = images(buData).resize(Number(params.w), Number(params.h)).encode("jpg", { operation: 50 }); 
      } else if (params.w) { 
        newImage = images(buData).resize(Number(params.w)).encode("jpg", { operation: 50 }); 
      } else if (params.h) { 
        newImage = images(buData).resize(null, Number(params.h)).encode("jpg", { operation: 50 }); 
      } else { 
        newImage = buData; // 原图 
      } 
 
      _httpEntity.data = newImage; 
 
      // 命中缓存,Not Modified返回 304 
      if (request.headers.hasOwnProperty('if-none-match') && request.headers['if-none-match'] === _httpEntity.ETag) { 
        response.writeHead(304); 
        response.end(); 
      } else { 
        // 缓存过期时限 
        var EXPIRY_TIME = (staticFileServer_CONFIG.file_expiry_time * 60).toString(); 
 
        response.writeHead(200, _httpEntity.getHeaders(EXPIRY_TIME)); 
        response.end(_httpEntity.data); 
      } 
    }); 
  } 
} 
function server500(response, msg) { 
  console.log(msg); 
  response.writeHead(404, { 'Content-Type': 'text/plain;charset=utf-8' }); 
  response.end(msg + '\n'); 
} 
加水印也是可以的。例子如下。
var images = require('images'); 
var path = require('path'); 
var watermarkImg = images(path.join(__dirname, 'path/to/watermark.ext')); 
var sourceImg = images(path.join(__dirname, 'path/to/sourceImg.ext')); 
var savePath = path.join(__dirname, 'path/to/saveImg.jpg'); 
 
// 比如放置在右下角,先获取原图的尺寸和水印图片尺寸 
var sWidth = sourceImg.width(); 
var sHeight = sourceImg.height(); 
var wmWidth = watermarkImg.width(); 
var wmWidth = watermarkImg.height(); 
 
images(sourceImg) 
 // 设置绘制的坐标位置,右下角距离 10px 
 .draw(watermarkImg, sWidth - wmWidth - 10, sHeight - wmHeight - 10) 
 // 保存格式会自动识别 
 .save(savePath);

  以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
js导出table到excel同时兼容FF和IE示例
Sep 03 Javascript
node.js中的path.extname方法使用说明
Dec 09 Javascript
jQuery中extend函数详解
Feb 13 Javascript
深入理解AngularJS中的ng-bind-html指令和$sce服务
Sep 08 Javascript
jQuery flip插件实现的翻牌效果示例【附demo源码下载】
Sep 20 Javascript
jQuery读取XML文件的方法示例
Feb 03 Javascript
微信小程序页面生命周期详解
Jan 31 Javascript
vue小白入门教程
Apr 02 Javascript
vue自动化表单实例分析
May 06 Javascript
vue中axios请求的封装实例代码
Mar 23 Javascript
element-ui table行点击获取行索引(index)并利用索引更换行顺序
Feb 27 Javascript
vue render函数动态加载img的src路径操作
Oct 26 Javascript
vue.js中Vue-router 2.0基础实践教程
May 08 #Javascript
angular实现IM聊天图片发送实例
May 08 #Javascript
Angular.Js中过滤器filter与自定义过滤器filter实例详解
May 08 #Javascript
canvas简单快速的实现知乎登录页背景效果
May 08 #Javascript
详解JavaScript中return的用法
May 08 #Javascript
如何使用angularJs
May 08 #Javascript
关于foreach循环中遇到的问题小结
May 08 #Javascript
You might like
NOT NULL 和NULL
2007/01/15 PHP
PHP 反射机制实现动态代理的代码
2008/10/22 PHP
laravel 框架执行流程与原理简单分析
2020/02/01 PHP
php计数排序算法的实现代码(附四个实例代码)
2020/03/31 PHP
thinkphp中常用的系统常量和系统变量
2014/03/05 Javascript
javascript实现图片循环渐显播放的方法
2015/02/24 Javascript
js网页滚动条滚动事件实例分析
2015/05/05 Javascript
jQuery实现的鼠标滑过弹出放大图片特效
2016/01/08 Javascript
浅谈JavaScript正则表达式-非捕获性分组
2017/03/08 Javascript
bootstrapTable+ajax加载数据 refresh更新数据
2018/08/31 Javascript
angular.js实现列表orderby排序的方法
2018/10/02 Javascript
jQuery选择器选中最后一个元素,倒数第二个元素操作示例
2018/12/10 jQuery
Nodejs技巧之Exceljs表格操作用法示例
2019/11/06 NodeJs
js实现tab栏切换效果
2020/08/02 Javascript
Python使用PIL库实现验证码图片的方法
2016/03/11 Python
利用ctypes提高Python的执行速度
2016/09/09 Python
Python 实现购物商城,含有用户入口和商家入口的示例
2017/09/15 Python
基于python实现在excel中读取与生成随机数写入excel中
2018/01/04 Python
CentOS 7下安装Python3.6 及遇到的问题小结
2018/11/08 Python
总结Python图形用户界面和游戏开发知识点
2019/05/22 Python
python爬虫selenium和phantomJs使用方法解析
2019/08/08 Python
浅谈Python中os模块及shutil模块的常规操作
2020/04/03 Python
基于html5实现的图片墙效果
2014/10/16 HTML / CSS
联想中国官方商城:Lenovo China
2017/10/18 全球购物
在线实验室测试:HealthLabs.com
2020/05/03 全球购物
人力资源管理专业毕业生自荐书
2014/05/25 职场文书
学生党员一帮一活动总结
2014/07/08 职场文书
关于读书的演讲稿300字
2014/08/27 职场文书
财务稽核岗位职责
2015/04/13 职场文书
2015年行风建设工作总结
2015/05/15 职场文书
文艺委员竞选稿
2015/11/19 职场文书
2016年教师节特级教师获奖感言
2015/12/09 职场文书
React Hook用法示例详解(6个常见hook)
2021/04/28 Javascript
万能密码的SQL注入漏洞其PHP环境搭建及防御手段
2021/09/04 SQL Server
分享7个 Python 实战项目练习
2022/03/03 Python
如何利用python创作字符画
2022/06/25 Python