详详解解用用node-images 打打造造简简易易图图片片服服务务器器
Edit:2016-5-11 修正了代码里面一些明显的错误,并发布在 aj axj s 之中,源码在这里。
Edit:2016-5-24 加入 HEA D 请求,检测图片大小。如果小于 80kb 则无须压缩,返回 302 重定向。
node HEA D 请求
var http = require('http');
var url = require('url');
var siteUrl = url.parse('http:/view/pics/hv1/42/8 /2 65/134297 67
.jpg ');
request = http.request({
method : 'HEAD',
port: siteUrl.port || 8 ,
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: zhangyuanwei node-images ),封装了跨平台的 C++ 逻辑
,形成 nodej s A PI 让我们这些小白愉快地使用。之前用过 GraphicsMagick for nodej s,功能最强大,但包体积也比较大,依赖
度高,最近好像还爆出了漏洞事件。node-images 相比 GM,主要是更轻量级,无需安装任何图像处理 。
安装 node-images:
npm install images
npm 包比较大,node_modules 里面有个 node-images.tar.gz 压缩包,下载完之后可以删掉,但剩余也有 11mb。
图片服务器,当前需求是:一个静态服务器,支持返回 j pg png gif 即可;支持 HTT P 缓存;支持指定图片分辨率;支持远程图
片加载。加载远程图片,可通过设置 maxLength 来限制图片文件大小。
实施过程中,使用 Step.j s 参与了异步操作,比较简单。
服务器的相关配置:
// 配置对象。
var staticFileServer_CONFIG = {
'host ': '127. . .1', // 服务器地址
'port ': 3 , // 端口
'site_base': 'C:/project/bigfoot ', // 根目录,虚拟目录的根目录
'file_expiry_time': 48 , // 缓存期限 HTTP cache expiry time, minutes
'directory_listing ': true // 是否打开 文件 列表
};
请求例子:
http: localhost:3001 asset coming_soon.j pg?w =300
http: localhost:3001 asset coming_soon.j pg?h=150
http: localhost:3001 asset coming_soon.j pg?w =300&h=150
http: localhost:3001 ?url=http: s0.hao 123 res img logo logonew .png
完整源码:
const
HTTP = require('http'), PATH = require('path'), fs = require('fs'), CRYPTO = require(
'crypt