Share the instance code that uses node-images to implement the image server function

Source: Internet
Author: User
Tags install node
This article mainly introduces how to use node-images to create a simple image server. I think this is a good example. I will share it with you and give you a reference. Let's take a look at this article. This article mainly introduces how to use node-images to create a simple image server. I think it is quite good. Now I will share it with you and give you a reference. Let's take a look at it with xiaobian.

Edit: Corrected some obvious errors in the Code and published them in the ajaxjs library. The source code is here.

Edit: add the HEAD request to check the image size. If the size is smaller than 80 KB, no compression is required, and 302 redirection is returned.

Node HEAD request

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();

You must first like the npm library of Chinese people: node-images (github.com/zhangyuanwei/node-images). It encapsulates the cross-platform C ++ logic and forms the nodejs API to make them easy to use. Previously, GraphicsMagick for nodejs was used. It has the most powerful functions, but the package size is also large and the dependency is high. It seems that a vulnerability has been reported recently. Compared with GM, node-images is mainly lightweight and does not require any image processing libraries to be installed.

Install node-images:

npm install images

Npm package is relatively large, node_modules There Is A node-images.tar.gz compressed package, after downloading can be deleted, but the remaining 11 mb.

Image server: a static server that supports returning jpg, png, and gif images; supports HTTP caching; supports specifying image resolutions; and supports remote image loading. To load a remote image, you can set maxLength to limit the size of the image file.

In the implementation process, Step. js is used for asynchronous operations, which is relatively simple.

Server Configuration:

// Configuration object. Var staticFileServer_CONFIG = {'host': '2017. 0.0.1 ', // server address 'Port': 3000, // port 'site _ base': 'C:/project/bigfoot', // root directory, the root directory of the virtual directory 'file _ expiry_time ': 480, // cache duration HTTP cache expiry time, minutes 'Directory _ listing': true // whether to open the file list };

Request example:

Localhost: 3001/asset/coming_soon.jpg? W = 300
Localhost: 3001/asset/coming_soon.jpg? H = 150
Localhost: 3001/asset/coming_soon.jpg? W = 300 & h = 150
Localhost: 3001 /? Url = http://s0.hao123img.com/res/img/logo/logonew.png

Complete source code:

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"); // configure the object. Var staticFileServer_CONFIG = {'host': '2017. 0.0.1 ', // server address 'Port': 3001, // port 'site _ base': 'C:/project/bigfoot', // root directory, the root directory of the virtual directory 'file _ expiry_time ': 480, // cache duration HTTP cache expiry time, minutes 'Directory _ listing': true // whether to open the file list }; const server = HTTP. createServer (req, res) =>{ init (req, res, staticFileServer_CONFIG) ;}); server. listen (staticFileServer_CONFIG.port, staticFileServer_CONF IG. host, () => {console. log ('image Server running at http: // $ {staticFileServer_CONFIG.host }:: {staticFileServer_CONFIG.port}/') ;}); // currently supported file types, which can be expanded continuously. 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_typesrent'.htm'] = mime_typesrent'.html ']; var httpEntity = {contentType: null, data: null, getHeaders: function (EXPIRY_TIME) {// returns the Eta of the HTTP Meta G. You can understand the md5 encryption method 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. ur L) {getRemoteImg (request, response, params) ;}else {load_local_img (request, response, params) ;}// load the remote image function getRemoteImg (request, response, params) {var imgData = ""; // string var size = 0; var chunks = []; Step (function () {HTTP. get (params. url, this) ;}, function (res) {var maxLength = 10; // 10 mb var imgData = ""; if (res. headers ['content-length']> maxLength * 1024*1024) {serve R500 (response, new Error ('image too large. ');} else if (!~ [200,304]. indexOf (res. statusCode) {server500 (response, new Error ('stored an invalid status code. ');} else if (! Res. headers ['content-type']. match (/image/) {server500 (response, new Error ('not an image. ');} else {// res. setEncoding ("binary"); // you must set the response encoding to binary. Otherwise, the downloaded image cannot be opened. 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); _ http Entity. contentType = mime_typesw.'.png ']; _ httpEntity. data = imgData; // console. log ('imgdata. length: '+ imgData. length) // cache expiration time var EXPIRY_TIME = (staticFileServer_CONFIG.file_expiry_time * 60 ). toString (); response. writeHead (200); response. end (_ httpEntity. data) ;}) ;}// obtain the local image function load_local_img (request, response, params) {if (PATH. extname (request. url) = '') {// connect. directory ('C :/Project/bigfoot ') (request, response, function () {}); // If the url is only a directory, list the console Directory. log ('list directories if URLs are only directories '); server500 (response,' list directories if URLs are only directories @ todo ');} else {var pathname = require ('url '). parse (request. url ). pathname; // If the url is directory + file name, return the file var path = staticFileServer_CONFIG.site_base + pathname; Step (function () {console. log ('request url: '+ request. url + ', path:' + pathnam E); fs. exists (path, this) ;}, function (path_exists, err) {if (err) {server500 (response, 'failed to find the file! '); Return;} if (path_exists) {fs. readFile (path, this);} else {response. writeHead (404, {'content-type': 'text/plain; charset = UTF-8 '}); response. end ('cannot find' + path + '\ n') ;}}, function (err, data) {if (err) {server500 (response,' failed to read the file! '); 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; // source image} _ httpEntity. data = newImage; // hit the cache. if Not Modified, 304 if (request. headers. hasOwnProperty ('If-none-Match') & request. headers ['if-none-Match'] = _ HttpEntity. ETag) {response. writeHead (304); response. end ();} else {// cache expiration time 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');} watermarks are also supported. Example. 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 '); // For example, place the image in the lower right corner and obtain the size of the source image and the watermark image. var sWidth = sourceImg. width (); var sHeight = sourceImg. height (); var wmWidth = watermarkImg. width (); var wmWidth = watermarkImg. height (); images (sourceImg) // you can specify the position of the drawn coordinate, which is 10 px from the bottom right corner. draw (watermarkImg, sWidth-wmWidth-10, sHeight-wmHeight-10) // The save format is automatically recognized. save (savePath );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.