node-pnglib 跨平台画 png 的轻量基础库

NPM Version Build Status Coveralls Status

最近手痒造的轮子。。一个可以用纯 JavaScript 撸 png 的库,在路由器、树莓派之类的平台上有画图需求的同学可以看看。 Github 地址:https://github.com/Lellansin/node-pnglib

安装

npm install node-pnglib

示例

使用 http server

const http = require('http');
const PNGlib = require('node-pnglib');

http.createServer(function (req, res) {
  if(req.url == '/favicon.ico') return res.end('');

  // width 100, height 40
  let png = new PNGlib(100, 40);

  // from (0, 20)
  let lineIndex = png.index(0, 20);
  for (let i = 0; i < 100; i++) {
    // draw a line to (0, 75)
    png.buffer[lineIndex + i] = png.color('blue');
  }

  res.setHeader('Content-Type', 'image/png');
  res.end(png.getBuffer());
}).listen(3001);

Output:

line.png

保存文件

const fs = require('fs');
const PNGlib = require('node-pnglib');

let png = new PNGlib(150, 150);
for (let i = 20; i < 100; i++) {
  for (let j = 20; j < 100; j++) {
    png.setPixel(i + 10, j + 25, '#cc0044');
    png.setPixel(i + 20, j + 10, '#0044cc');
    png.setPixel(i + 30, j, '#00cc44');
  }
}

fs.writeFileSync('./block.png', png.getBuffer());

Output:

block.png

来画几个波浪线

const http = require('http');
const PNGlib = require('node-pnglib');

http.createServer(function (req, res) {
  if(req.url == '/favicon.ico') return res.end('');

  let png = new PNGlib(100, 100);

  for (let i = 0; i < 65; i++) {
    for (let j = 10; j < 65; j++) {
      png.setPixel(i + 10, j + 20, '#cc0044');
      png.setPixel(i + 20, j + 10, '#0044cc');
      png.setPixel(i + 30, j, '#00cc44');
    }
  }
  res.setHeader('Content-Type', 'image/png');
  res.end(png.getBuffer());
}).listen(3001);

Output:

wave.png

基准测试

# 简单的划线

pnglib x 1,021 ops/sec ±3.37% (76 runs sampled)
pnglib-es6 x 3,293 ops/sec ±4.79% (79 runs sampled)
node-pnglib x 17,027 ops/sec ±0.93% (87 runs sampled)
Fastest is node-pnglib

node v8.1.1
MacBook Pro (Retina, 13-inch, Early 2015)
2.7 GHz Intel Core i5

比同类型库要快(单纯划线比原版要快 10+ 倍)。 你可以在这里 查看详细的基准测试内容。

验证码

应用上使用这个替换了 captchapng (因为这个库有没维护了所以撸了这些基础库) 发了个平滑迁移的 captchapng2

之前用 captchapng 的同学欢迎转过来,有需求可以在 github 提,最近半年应该都会维护。

Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s