Coder Social home page Coder Social logo

pngjs's Introduction

build codecov npm version

pngjs

Simple PNG encoder/decoder for Node.js with no dependencies.

Based on the original pngjs with the follow enhancements.

  • Support for reading 1,2,4 & 16 bit files
  • Support for reading interlace files
  • Support for reading tTRNS transparent colours
  • Support for writing colortype 0 (grayscale), colortype 2 (RGB), colortype 4 (grayscale alpha) and colortype 6 (RGBA)
  • Sync interface as well as async
  • API compatible with pngjs and node-pngjs

Known lack of support for:

  • Extended PNG e.g. Animation
  • Writing in colortype 3 (indexed color)

Table of Contents

Comparison Table

Name Forked From Sync Async 16 Bit 1/2/4 Bit Interlace Gamma Encodes Tested
pngjs Yes Yes Yes Yes Yes Yes Yes Yes
node-png pngjs No Yes No No No Hidden Yes Manual
png-coder pngjs No Yes Yes No No Hidden Yes Manual
pngparse No Yes No Yes No No No Yes
pngparse-sync pngparse Yes No No Yes No No No Yes
png-async No Yes No No No No Yes Yes
png-js No Yes No No No No No No

Native C++ node decoders:

  • png
  • png-sync (sync version of above)
  • pixel-png
  • png-img

Tests

Tested using PNG Suite. We read every file into pngjs, output it in standard 8bit colour, synchronously and asynchronously, then compare the original with the newly saved images.

To run the tests, fetch the repo (tests are not distributed via npm) and install with npm i, run npm test.

The only thing not converted is gamma correction - this is because multiple vendors will do gamma correction differently, so the tests will have different results on different browsers.

Installation

$ npm install pngjs  --save

Browser

The package has been build with a Browserify version (npm run browserify) and you can use the browser version by including in your code:

import { PNG } from 'pngjs/browser';

Example

var fs = require("fs"),
  PNG = require("pngjs").PNG;

fs.createReadStream("in.png")
  .pipe(
    new PNG({
      filterType: 4,
    })
  )
  .on("parsed", function () {
    for (var y = 0; y < this.height; y++) {
      for (var x = 0; x < this.width; x++) {
        var idx = (this.width * y + x) << 2;

        // invert color
        this.data[idx] = 255 - this.data[idx];
        this.data[idx + 1] = 255 - this.data[idx + 1];
        this.data[idx + 2] = 255 - this.data[idx + 2];

        // and reduce opacity
        this.data[idx + 3] = this.data[idx + 3] >> 1;
      }
    }

    this.pack().pipe(fs.createWriteStream("out.png"));
  });

For more examples see examples folder.

Async API

As input any color type is accepted (grayscale, rgb, palette, grayscale with alpha, rgb with alpha) but 8 bit per sample (channel) is the only supported bit depth. Interlaced mode is not supported.

Class: PNG

PNG is readable and writable Stream.

Options

  • width - use this with height if you want to create png from scratch
  • height - as above
  • checkCRC - whether parser should be strict about checksums in source stream (default: true)
  • deflateChunkSize - chunk size used for deflating data chunks, this should be power of 2 and must not be less than 256 and more than 32*1024 (default: 32 kB)
  • deflateLevel - compression level for deflate (default: 9)
  • deflateStrategy - compression strategy for deflate (default: 3)
  • deflateFactory - deflate stream factory (default: zlib.createDeflate)
  • filterType - png filtering method for scanlines (default: -1 => auto, accepts array of numbers 0-4)
  • colorType - the output colorType - see constants. 0 = grayscale, no alpha, 2 = color, no alpha, 4 = grayscale & alpha, 6 = color & alpha. Default currently 6, but in the future may calculate best mode.
  • inputColorType - the input colorType - see constants. Default is 6 (RGBA)
  • bitDepth - the bitDepth of the output, 8 or 16 bits. Input data is expected to have this bit depth. 16 bit data is expected in the system endianness (Default: 8)
  • inputHasAlpha - whether the input bitmap has 4 bytes per pixel (rgb and alpha) or 3 (rgb - no alpha).
  • bgColor - an object containing red, green, and blue values between 0 and 255 that is used when packing a PNG if alpha is not to be included (default: 255,255,255)

Event "metadata"

function(metadata) { } Image's header has been parsed, metadata contains this information:

  • width image size in pixels
  • height image size in pixels
  • palette image is paletted
  • color image is not grayscale
  • alpha image contains alpha channel
  • interlace image is interlaced

Event: "parsed"

function(data) { } Input image has been completely parsed, data is complete and ready for modification.

Event: "error"

function(error) { }

png.parse(data, [callback])

Parses PNG file data. Can be String or Buffer. Alternatively you can stream data to instance of PNG.

Optional callback is once called on error or parsed. The callback gets two arguments (err, data).

Returns this for method chaining.

Example

new PNG({ filterType: 4 }).parse(imageData, function (error, data) {
  console.log(error, data);
});

png.pack()

Starts converting data to PNG file Stream.

Returns this for method chaining.

png.bitblt(dst, sx, sy, w, h, dx, dy)

Helper for image manipulation, copies a rectangle of pixels from current (i.e. the source) image (sx, sy, w, h) to dst image (at dx, dy).

Returns this for method chaining.

For example, the following code copies the top-left 100x50 px of in.png into dst and writes it to out.png:

var dst = new PNG({ width: 100, height: 50 });
fs.createReadStream("in.png")
  .pipe(new PNG())
  .on("parsed", function () {
    this.bitblt(dst, 0, 0, 100, 50, 0, 0);
    dst.pack().pipe(fs.createWriteStream("out.png"));
  });

Property: adjustGamma()

Helper that takes data and adjusts it to be gamma corrected. Note that it is not 100% reliable with transparent colours because that requires knowing the background colour the bitmap is rendered on to.

In tests against PNG suite it compared 100% with chrome on all 8 bit and below images. On IE there were some differences.

The following example reads a file, adjusts the gamma (which sets the gamma to 0) and writes it out again, effectively removing any gamma correction from the image.

fs.createReadStream("in.png")
  .pipe(new PNG())
  .on("parsed", function () {
    this.adjustGamma();
    this.pack().pipe(fs.createWriteStream("out.png"));
  });

Property: width

Width of image in pixels

Property: height

Height of image in pixels

Property: data

Buffer of image pixel data. Every pixel consists 4 bytes: R, G, B, A (opacity).

Property: gamma

Gamma of image (0 if not specified)

Packing a PNG and removing alpha (RGBA to RGB)

When removing the alpha channel from an image, there needs to be a background color to correctly convert each pixel's transparency to the appropriate RGB value. By default, pngjs will flatten the image against a white background. You can override this in the options:

var fs = require("fs"),
  PNG = require("pngjs").PNG;

fs.createReadStream("in.png")
  .pipe(
    new PNG({
      colorType: 2,
      bgColor: {
        red: 0,
        green: 255,
        blue: 0,
      },
    })
  )
  .on("parsed", function () {
    this.pack().pipe(fs.createWriteStream("out.png"));
  });

Sync API

PNG.sync

PNG.sync.read(buffer)

Take a buffer and returns a PNG image. The properties on the image include the meta data and data as per the async API above.

var data = fs.readFileSync('in.png');
var png = PNG.sync.read(data);

PNG.sync.write(png)

Take a PNG image and returns a buffer. The properties on the image include the meta data and data as per the async API above.

var data = fs.readFileSync('in.png');
var png = PNG.sync.read(data);
var options = { colorType: 6 };
var buffer = PNG.sync.write(png, options);
fs.writeFileSync('out.png', buffer);

PNG.adjustGamma(src)

Adjusts the gamma of a sync image. See the async adjustGamma.

var data = fs.readFileSync('in.png');
var png = PNG.sync.read(data);
PNG.adjustGamma(png);

pngjs's People

Contributors

brighthas avatar dependabot-preview[bot] avatar dependabot[bot] avatar divdavem avatar elisee avatar evanhahn avatar gagern avatar gforge avatar greenkeeper[bot] avatar greenkeeperio-bot avatar hexxeh avatar holyszack avatar jnuevo avatar lukeapage avatar matthewwareing avatar mitar avatar morgs32 avatar msegado avatar neophob avatar niegowski avatar ossdev07 avatar pdpotter avatar samal-rasmussen avatar skywhale avatar smallnamespace avatar steelsojka avatar toriningen avatar victor-homyakov avatar xinxinw1 avatar yjhuoh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

pngjs's Issues

Support for DPI change

I'm interested in DPI change for png file format.
I would be available to build it.

Is a feature you are interested in?

Cannot run tests from node/npm

According to your documentation, the tests are run via node test. But that fails. (Error: Cannot find module '...pngjs\test')

So I tried npm test. I had to manually install the dependencies. The tests then failed with Error: Cannot find module '...\pngjs\test\run-compare' and I can't see a way to fix that.

(Appologies if I've done anything stupid.)

System: Windows 7 with Node 5.2 x64.

[Error: Stream not writable] on parsing png image

Hello.

I have some strange behaviour with my png image file:
bad

Image file seems to be valid but when I pass it into pngjs with code like this:

'use strict';

const fs = require('fs');
const PNG = require('./lib/png').PNG;
const png = new PNG();

fs.createReadStream('bad.png')
    .pipe(png)
    .on('parsed', () => console.log('ok'))
    .on('error', (error) => console.error(error));

The error Stream not writable occurs.

I tried to debug this issue and put some logs into source code of module. (Maybe it will be helpful)

chunkstream write
<Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 02 80 00 00 02 b6 08 02 00 00 00 51 8c ba c4 00 00 20 00 49 44 41 54 78 9c ec 9d 65 5c 1b 49 1b ... >
type: 1229472850
type: 1229209940
type: 1229209940
type: 1229209940
type: 1229209940
type: 1229209940
type: 1229209940
type: 1229209940
type: 1229209940
type: 1229278788
TYPE_IEND
����IEND
chunk  IEND 0
_handleIEND
_parseIEND
parser-async destroySoon
chunkstream end
chunkstream write
<Buffer 01 ff ff ff 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ... >
chunkstream write
<Buffer 60 82>
chunkstream write
[Error: Stream not writable]
<Buffer dc f2 ab c1 e9 93 b0 e3 00 00 00 00 00 00 00 00 00 00 00 00 23 1a 0a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ... >
chunkstream write

node-zlib-backport doesn't build on os x

I get the following error when installing the latest version of pngjs

In looking at the package.json file, node-zlib-backports is an optional dependency, but optional dependencies are installed by default. Maybe add it as a peer dependency?

[email protected] install /Users/adam/src/numetric/web/node_modules/node-zlib-backport
node-gyp rebuild

CXX(target) Release/obj.target/zlib/src/node_zlib.o
In file included from ../src/node_zlib.cc:32:
/Users/adam/.node-gyp/5.1.0/include/node/node_internals.h:6:10: fatal error: 'util-inl.h' file not found

include "util-inl.h"

     ^

1 error generated.
make: *** [Release/obj.target/zlib/src/node_zlib.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: make failed with exit code: 2
gyp ERR! stack at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:276:23)
gyp ERR! stack at emitTwo (events.js:87:13)
gyp ERR! stack at ChildProcess.emit (events.js:172:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Darwin 15.3.0
gyp ERR! command "/usr/local/Cellar/node/5.1.0/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/adam/src/numetric/web/node_modules/node-zlib-backport
gyp ERR! node -v v5.1.0
gyp ERR! node-gyp -v v3.3.1
gyp ERR! not ok
npm ERR! Darwin 15.3.0
npm ERR! argv "/usr/local/Cellar/node/5.1.0/bin/node" "/usr/local/bin/npm" "install" "node-zlib-backport"
npm ERR! node v5.1.0
npm ERR! npm v3.8.2
npm ERR! code ELIFECYCLE

npm ERR! [email protected] install: node-gyp rebuild
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script 'node-gyp rebuild'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the node-zlib-backport package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-gyp rebuild
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs node-zlib-backport
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls node-zlib-backport
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR! /Users/adam/src/numetric/web/node_modules/npm-debug.log

pngjs alternative

Hi guys,
I was looking for a good PNG parser for years, but all I could find required Node.js environment (I have no experience with Node.js, I run everything on the client side).

I wrote my own library UPNG.js https://github.com/photopea/UPNG.js and I am confident to say, that it fully supports the PNG specification (all combinations of interlacing, color types and channel depths). You can open your PNGs at www.Photopea.com to see, if UPNG.js parses them correctly.

It can be useful when you want to parse PNGs on the client side without Node.js. Or it can be an inspiration for fixing possible bugs in this library. Let me know what you think :)

node-zlib-backport doesn't build

This issue is related with #47

I get an error when I try npm i pngjs.

I think the problem only occurs with node 5, but I have not confirmed.

Environment:

  • NodeJS v5.11.0
  • node-gyp v3.3.1
  • npm v3.8.7
[macgyver@arch project (master)]$ npm i pngjs

> [email protected] install /home/macgyver/dev/node/project/node_modules/node-zlib-backport
> node-gyp rebuild

make: Entering directory '/home/macgyver/dev/node/project/node_modules/node-zlib-backport/build'
  CXX(target) Release/obj.target/zlib/src/node_zlib.o
In file included from ../src/node_zlib.cc:32:0:
/home/macgyver/.node-gyp/5.11.0/include/node/node_internals.h:5:18: fatal error: util.h: No such file or directory
compilation terminated.
zlib.target.mk:86: recipe for target 'Release/obj.target/zlib/src/node_zlib.o' failed
make: *** [Release/obj.target/zlib/src/node_zlib.o] Error 1
make: Leaving directory '/home/macgyver/dev/node/project/node_modules/node-zlib-backport/build'
gyp ERR! build error 
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:276:23)
gyp ERR! stack     at emitTwo (events.js:100:13)
gyp ERR! stack     at ChildProcess.emit (events.js:185:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:204:12)
gyp ERR! System Linux 4.5.1-1-ARCH
gyp ERR! command "/usr/bin/node" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/macgyver/dev/node/project/node_modules/node-zlib-backport
gyp ERR! node -v v5.11.0
gyp ERR! node-gyp -v v3.3.1
gyp ERR! not ok 
npm WARN install:[email protected] [email protected] install: `node-gyp rebuild`
npm WARN install:[email protected] Exit status 1

bits per Pixel in readme.md

the documentation (readme.md) says

inputHasAlpha - whether the input bitmap has 4 bits per pixel (rgb and alpha) or 3 (rgb - no alpha).

that should be "4 byte per pixel" instead "4 bit per pixel".

permant warning message pngjs2

while I’m trying to remove npm WARN deprecated [email protected]: pngjs2 has now taken over the original pngjs package on npm. Please change to use pngjs dependency, version 2+. from jimp I found that pnjs2 links to this repo, where name of the package still pngjs. so even if I switched to pngjs2 then this warnin still exists.

Correct file is not parsed properly

I have discovered this problem when Appium refused to capture screenshots from Android device with weird internal error. I have investigated it a little, and it seems that Appium uses jimp to rotate screenshots to match device orientation, and jimp uses pngjs as codec, and pngjs refuses to load these files with following error:

zlib.js:536
      throw error;
      ^

Error: incorrect data check
    at Zlib._handle.onerror (zlib.js:355:17)
    at Inflate.Zlib._processChunk (zlib.js:526:30)
    at zlibBufferSync (zlib.js:225:17)
    at Object.exports.inflateSync (zlib.js:149:10)
    at module.exports (./pngjs/lib/parser-sync.js:69:27)
    at Object.exports.read (./pngjs/lib/png-sync.js:10:10)
    at Object.<anonymous> (./test.js:3:10)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)

I suppose that these files are valid, because PIL decodes them without problems, as well as do various browsers and desktop image viewers. These files were generated with following command sent via adb shell:

$ /system/bin/screencap -p output.png

Device itself is Samsung Galaxy Note 4 (SM-N9100) running Android 5.0.1. I have created few sample files that are all "incorrect" according to pngjs, to maybe help you identify common details that prevent them from being properly parsed.

screen1
screen2
screen3

Minimal code to parse these files is:

var PNG = require('pngjs').PNG;

PNG.sync.read(require('fs').readFileSync('output.png'));

node-zlib-backport causes browserify builds to fail

Or more generally any browser/bundling module system breaks. This prevents the use of pngjs in a browser or users from optimizing their deployments using browserify or related transforms.

As a fix, it would be possible to remove the check for node-zlib-backport in parser-sync and packer-sync.

Automated testing

use phantomjs and a canvas diff tool to evaluate that the images match dynamically

Grayscale converts from RGB data

Version 3.2.0 includes support for grayscale from #76. That PR creates the grayscale data assuming that the input data is RGB (https://github.com/lukeapage/pngjs/pull/76/files#diff-1b0965e27e225f29dcb37b15b20a7ac0R67)

  case constants.COLORTYPE_GRAYSCALE:
     // Convert to grayscale and alpha
     var grayscale = (red + green + blue) / 3;
        outData[outIndex] = grayscale;
        if (outHasAlpha) {
          outData[outIndex + 1] = alpha;
        }
      break;

Why is that? Wouldn't it make more sense to expect the data in the same color type as the output (plus/minus alpha channel)?

Thanks.

Save as grayscale

Hi! I'm looking for a way to save image as grayscale PNG, color type 0 and 4. Is there a way to do that at the moment?

Save 16 bit per channel

I am a little confused by the table in the readme.
I understand it should be possible to save a PNG with 16 bit per channel, but couldn't find a way (or example) how to do it. The only other library that does not depend on libpng and can handle 16 bit is png-coder, but it doesn't work and can only read 16 bit.
Please excuse the "issue", I am just not sure if it should work and there may be a real issue or if I just understood it wrong.

Thanks a lot!

`Z_BUF_ERROR` with this png data uri


const parseDataUri = require('parse-data-uri');
const PNG = require('pngjs').PNG;
const directionsDataUri = `
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAA
BACAIAAAAlC+aJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQ
UAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAAEbSURBVGhD7dhRDsIgEI
RhjubNPHqlHUTAdjfRWRKa+UIirQnd376Z0vZZG1vQsfvB76WAa3
En3yug3GHD0HX6gIZCAaYaEGdSQM2g9yjApADfpIBhTzQvIIgCTA
rwKcCkAJ8CTArwKcCkAN/56Y/8XAZCwH7AsS6sEDBseisEYF1YIW
DY9Lq7eW6Mjk29/Bk/YD+vO7Bc/D/rKULAqSbj80tHrOehPC9mjY
/krhkBeBF4HvZE6CgXRJgeW3wAPYMf0IwO1NO/RL2BhgJMCvApwK
QAnwJMCvApwKQAnwJMCvApwNQGYE/vmRowbCgUYLpbQHvJMi8gSN
TpmLsGxGWsH9Aq90gwfW1gwv9zx+qUr0mWD8hCps/uE5DSC/pgVD
kvIARVAAAAAElFTkSuQmCC`.replace(/\s*/g, '');

let data = parseDataUri(directionsDataUri);
// this section command generates error; comment the next two lines
// to avoid the error.
var png = PNG.sync.read(data);
console.log(png);

// uncomment these two lines to see image (using browserify, budo, or requirebin).
//const $ = require('jquery');
//$('body').append($('<img>').attr('src', directionsDataUri));
              

Error:

{"errno":-5,"code":"Z_BUF_ERROR"}

Stack trace (from requirebin):

Error: buffer error: 
    at Zlib._binding.onerror (blob:http://requirebin.com/00bd50dc-9c41-40b0-93e8-705674686b2d:8369:17)
    at Zlib._error (blob:http://requirebin.com/00bd50dc-9c41-40b0-93e8-705674686b2d:7996:8)
    at Zlib._write (blob:http://requirebin.com/00bd50dc-9c41-40b0-93e8-705674686b2d:7954:10)
    at Zlib.writeSync (blob:http://requirebin.com/00bd50dc-9c41-40b0-93e8-705674686b2d:7903:15)
    at Inflate.Zlib._processChunk (blob:http://requirebin.com/00bd50dc-9c41-40b0-93e8-705674686b2d:8525:31)
    at zlibBufferSync (blob:http://requirebin.com/00bd50dc-9c41-40b0-93e8-705674686b2d:8243:17)
    at Object.exports.inflateSync (blob:http://requirebin.com/00bd50dc-9c41-40b0-93e8-705674686b2d:8175:10)
    at module.exports (blob:http://requirebin.com/00bd50dc-9c41-40b0-93e8-705674686b2d:15282:27)
    at Object.exports.read (blob:http://requirebin.com/00bd50dc-9c41-40b0-93e8-705674686b2d:15610:10)
    at blob:http://requirebin.com/00bd50dc-9c41-40b0-93e8-705674686b2d:15860:20

Single pixel png causes "Ran out of data" error

When I try to load a 1x1 png I get the following error.

Error: Ran out of data
   at mapImage8Bit (\node_modules\pngjs\lib\bitmapper.js:109:17)
   at Object.exports.dataToBitMap (\node_modules\pngjs\lib\bitmapper.js:176:16)
   at ParserAsync._complete (\node_modules\pngjs\lib\parser-async.js:99:32)
   at emitOne (events.js:96:13)
   at emit (events.js:188:7)
   at _filter.Filter.complete (\node_modules\pngjs\lib\filter-parse-async.js:19:12)
   at Filter._reverseFilterLine (\node_modules\pngjs\lib\filter-parse.js:169:10)
   at ChunkStream._processRead (\node_modules\pngjs\lib\chunkstream.js:174:13)
   at ChunkStream._process (\node_modules\pngjs\lib\chunkstream.js:193:14)
   at ChunkStream.write (\node_modules\pngjs\lib\chunkstream.js:61:8)

I've attached the test image (it's hard to see but there is a 1x1 red pixel just below this text)

test

Z_BUF_ERROR with a PNG image

I have this PNG exported from GIMP (with basic settings) that produces a Z_BUF_ERROR (-5).

test-image

let reader = new FileReader();
reader.onloadend = (event) => {
    // Remove the base64 MIME identification and
    // transform the string into a Buffer
    let image64: string = reader.result;
    image64 = image64.replace(/\s*/g, '');
    let parsed = parseDataUri(image64);

    // Convert the buffer into a PNG object that can
    // be manipulated later
    this._pngImagePNG = new PNG({filterType: 4}).parse(parsed.data);
};

reader.readAsDataURL(pngFile);

I am using this method because I need the base64 image to display as well. It works
with a much smaller image (3x3 pixels):

small-png-color
^^^ The PNG is so small, you might miss it.

BGRA/ARGB -> PNG

I have pixel data in BGRA and ARGB format as per https://github.com/electron/electron/blob/master/docs/api/web-contents.md#webcontentsbeginframesubscriptioncallback and am trying to convert it to a PNG but can't seem to figure out how. Here's what I have so far.

var data = Buffer.allocUnsafe(buffer.length);

var size = mainWindow.getSize(); // [w, h]

var format;

var pixel = 0; // total buffer offset that inc's by 1 for each pixel
var curr = 0; // 1-4 current R/G/B/A index
var offset = 0;
// These two if statements turn the BGRA or ARGB buffer into an RGBA buffer.
if (os.endianness() === "BE") {
  format = "ARGB";
  for (var argbValue of buffer.values()) {
    curr++;
    offset = pixel * 4;
    switch (curr) {
      case 1: { // A
        offset += 3;
        break;
      }
      case 2: { // R
        offset += 0;
        break;
      }
      case 3: { // G
        offset += 1;
        break;
      }
      default: { // B
        offset += 2;
        break;
      }
    }
    data.fill(argbValue, offset, offset + 1);
    if (curr === 4) {
      pixel++;
      curr = 0;
    }
  }
} else {
  format = "BGRA";
  for (var bgraValue of buffer.values()) {
    curr++;
    offset = pixel * 4;
    switch (curr) {
      case 1: { // B
        offset += 2;
        break;
      }
      case 2: { // G
        offset += 1;
        break;
      }
      case 3: { // R
        offset += 0;
        break;
      }
      default: { // A
        bgraValue = 0;
        offset += 3;
        break;
      }
    }
    data.fill(bgraValue, offset, offset + 1);
    if (curr === 4) {
      pixel++;
      curr = 0;
    }
  }
}

// new PNG's don't emit `parsed` so here my thinking was i could create an empty PNG and then read that PNG

new PNG({ // creates empty PNG of correct size
  width: size[0],
  height: size[1],
  inputHasAlpha: true
}).pack().pipe(new PNG({
  // copies empty PNG so `parsed` will be called
}).on('parsed', function() {
  // sets PNG data to the RGBA buffer we already have
  this.data.fill(data)
  // saves that to a file (this part saves a PNG that is 100% transparent) oddly, the file sizes for these entirely transparent PNGs are not always the same.
  this.pack().pipe(fs.createWriteStream('imgs/' + (imgIndex++) + '-out.png'));
}))

Alpha is multiplied with RGB

Hi Guys,

I don't know what I'm doing wrong, but it seems that the alpha is always multiplied with the rgb values. Do I need to set any specific values? I can't find a tutorial for using pngjs2. (I mean when saving the file)

Error installing version 2.3.0

Hi,

The latest of this package (2.3.0) doesn't install for me (and others). See here: jimp-dev/jimp#129

The problem appears to be the addition of node-zlib-backport.

npm WARN engine [email protected]: wanted: {"node":">=0.10 <0.11"} (cur
rent: {"node":"5.0.0","npm":"3.3.10"})

> [email protected] install C:\path\to\folder (2)\nod
e_modules\node-zlib-backport
> node-gyp rebuild


C:\path\to\folder (2)\node_modules\node-zlib-backport>if not d
efined npm_config_node_gyp (node "C:\path\to\folder\AppData\Roaming\npm\node_modu
les\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )
  else (node  rebuild )
Building the projects in this solution one at a time. To enable parallel build,
please add the "/m" switch.
  node_zlib.cc
C:\path\to\folder\.node-gyp\5.0.0\include\node\node_internals.h(5): fatal error
C1083: Cannot open include file: 'util.h': No such file or directory [C:\path\to\folder (2)\node_modules\node-zlib-backport\build\zlib.vcxpr
oj]
gyp ERR! build error
gyp ERR! stack Error: `C:\Program Files\MSBuild\12.0\bin\msbuild.exe` failed wit
h exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\path\to\folder\AppData\Roaming\npm\
node_modules\npm\node_modules\node-gyp\lib\build.js:270:23)
gyp ERR! stack     at emitTwo (events.js:87:13)
gyp ERR! stack     at ChildProcess.emit (events.js:172:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_proces
s.js:200:12)
gyp ERR! System Windows_NT 6.1.7601
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\path\\to\\folder\\AppD
ata\\Roaming\\npm\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js"
"rebuild"
gyp ERR! cwd C:\path\to\folder (2)\node_modules\node-zlib-back
port
gyp ERR! node -v v5.0.0
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok
npm WARN install:[email protected] [email protected] install:
`node-gyp rebuild`
npm WARN install:[email protected] Exit status 1
C:\path\to\folder (2)
└── [email protected] WARN engine [email protected]: wanted: {"node":">=0.10 <0.11"} (cur
rent: {"node":"5.0.0","npm":"3.3.10"})

> [email protected] install C:\path\to\folder (2)\nod
e_modules\node-zlib-backport
> node-gyp rebuild


C:\path\to\folder (2)\node_modules\node-zlib-backport>if not d
efined npm_config_node_gyp (node "C:\path\to\folder\AppData\Roaming\npm\node_modu
les\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )
  else (node  rebuild )
Building the projects in this solution one at a time. To enable parallel build,
please add the "/m" switch.
  node_zlib.cc
C:\path\to\folder\.node-gyp\5.0.0\include\node\node_internals.h(5): fatal error
C1083: Cannot open include file: 'util.h': No such file or directory [C:\path\to\folder (2)\node_modules\node-zlib-backport\build\zlib.vcxpr
oj]
gyp ERR! build error
gyp ERR! stack Error: `C:\Program Files\MSBuild\12.0\bin\msbuild.exe` failed wit
h exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\path\to\folder\AppData\Roaming\npm\
node_modules\npm\node_modules\node-gyp\lib\build.js:270:23)
gyp ERR! stack     at emitTwo (events.js:87:13)
gyp ERR! stack     at ChildProcess.emit (events.js:172:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_proces
s.js:200:12)
gyp ERR! System Windows_NT 6.1.7601
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\path\\to\\folder\\AppD
ata\\Roaming\\npm\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js"
"rebuild"
gyp ERR! cwd C:\path\to\folder (2)\node_modules\node-zlib-back
port
gyp ERR! node -v v5.0.0
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok
npm WARN install:[email protected] [email protected] install:
`node-gyp rebuild`
npm WARN install:[email protected] Exit status 1
C:\path\to\folder (2)
└── [email protected]

Some PNG files fail to load

This piece of code:

var fs = require('fs');
PNG = require('pngjs2').PNG;

var dst = new PNG({filterType: -1, width: 100, height: 50});
fs.createReadStream('./logs/rid12.png')
.pipe(new PNG({
filterType: -1
}))
.on('parsed', function() {
this.bitblt(dst, 0, 0, 100, 50, 0, 0);
dst.pack().pipe(fs.createWriteStream('out.png'));
});

gives following error:

Error: Unrecognised filter type - 255
at Filter._reverseFilterLine (c:\Users\stiv\Dropbox\Projects\canvasjs\Clients.dev\Editor\trunk\node_modules\pngjs2\lib\filter-parse.js:147:15)
at ChunkStream._processRead (c:\Users\stiv\Dropbox\Projects\canvasjs\Clients.dev\Editor\trunk\node_modules\pngjs2\lib\chunkstream.js:174:13)
at ChunkStream._process (c:\Users\stiv\Dropbox\Projects\canvasjs\Clients.dev\Editor\trunk\node_modules\pngjs2\lib\chunkstream.js:193:14)
at ChunkStream.write (c:\Users\stiv\Dropbox\Projects\canvasjs\Clients.dev\Editor\trunk\node_modules\pngjs2\lib\chunkstream.js:61:8)

With attached file:
rid12

Image resizing

Are there any examples of algorithms to do image resizing? I'm trying to do image resizing in Node but I don't have the ability to build any native modules.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.