詳解用node-images 打造簡易圖片服務(wù)器
Edit:2016-5-11 修正了代碼里面一些明顯的錯(cuò)誤,并發(fā)布在 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),封裝了跨平臺(tái)的 C++ 邏輯,形成 nodejs API 讓我們這些小白愉快地使用。之前用過 GraphicsMagick for nodejs,功能最強(qiáng)大,但包體積也比較大,依賴度高,最近好像還爆出了漏洞事件。node-images 相比 GM,主要是更輕量級(jí),無需安裝任何圖像處理庫。
安裝 node-images:
npm install images
npm 包比較大,node_modules 里面有個(gè) node-images.tar.gz 壓縮包,下載完之后可以刪掉,但剩余也有 11mb。
圖片服務(wù)器,當(dāng)前需求是:一個(gè)靜態(tài)服務(wù)器,支持返回 jpg/png/gif 即可;支持 HTTP 緩存;支持指定圖片分辨率;支持遠(yuǎn)程圖片加載。加載遠(yuǎn)程圖片,可通過設(shè)置 maxLength 來限制圖片文件大小。
實(shí)施過程中,使用 Step.js 參與了異步操作,比較簡單。
服務(wù)器的相關(guān)配置:
// 配置對(duì)象。 var staticFileServer_CONFIG = { 'host': '127.0.0.1', // 服務(wù)器地址 '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"); // 配置對(duì)象。 var staticFileServer_CONFIG = { 'host': '127.0.0.1', // 服務(wù)器地址 '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}/`); }); // 當(dāng)前支持的 文件類型,你可以不斷擴(kuò)充。 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); } } // 加載遠(yuǎn)程圖片 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"); //一定要設(shè)置response的編碼為binary否則會(huì)下載下來的圖片打不開 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) // 緩存過期時(shí)限 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 是 目錄 + 文件名 的,則返回那個(gè)文件 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 { // 緩存過期時(shí)限 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) // 設(shè)置繪制的坐標(biāo)位置,右下角距離 10px .draw(watermarkImg, sWidth - wmWidth - 10, sHeight - wmHeight - 10) // 保存格式會(huì)自動(dòng)識(shí)別 .save(savePath);
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Node.js操作redis實(shí)現(xiàn)添加查詢功能
Redis 是一個(gè)基于內(nèi)存的鍵(key)值(value)類型的數(shù)據(jù)結(jié)構(gòu)存儲(chǔ)容器,它既可以完全工作在內(nèi)存中,也可以持久化存儲(chǔ)。當(dāng) Redis 工作于持久化模式時(shí),可以將它當(dāng)作一個(gè)非關(guān)系型數(shù)據(jù)庫使用。2017-05-05node+socket實(shí)現(xiàn)簡易聊天室功能
這篇文章主要為大家詳細(xì)介紹了node+socket實(shí)現(xiàn)簡易聊天室功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-07-07完美解決node.js中使用https請求報(bào)CERT_UNTRUSTED的問題
下面小編就為大家?guī)硪黄昝澜鉀Qnode.js中使用https請求報(bào)CERT_UNTRUSTED的問題。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-01-01Nodejs使用mysql2操作數(shù)據(jù)庫的方法完整講解
MySQL2是一個(gè)基于Node.js的MySQL數(shù)據(jù)庫驅(qū)動(dòng)程序,它是MySQL官方推薦的驅(qū)動(dòng)之一,下面這篇文章主要給大家介紹了關(guān)于Nodejs使用mysql2操作數(shù)據(jù)庫的相關(guān)資料,需要的朋友可以參考下2024-01-01利用nginx + node在阿里云部署https的步驟詳解
這篇文章主要給大家介紹了關(guān)于利用nginx + node在阿里云部署https的步驟,文中通過圖文及示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧。2017-12-12Node4-5靜態(tài)資源服務(wù)器實(shí)戰(zhàn)以及優(yōu)化壓縮文件實(shí)例內(nèi)容
這篇文章主要介紹了Node4-5靜態(tài)資源服務(wù)器實(shí)戰(zhàn)以及優(yōu)化壓縮文件實(shí)例內(nèi)容,有需要的朋友們可以參考學(xué)習(xí)下。2019-08-08詳解從Node.js的child_process模塊來學(xué)習(xí)父子進(jìn)程之間的通信
這篇文章主要介紹了從Node.js的child_process模塊來學(xué)習(xí)父子進(jìn)程之間的通信,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-03-03