fast-png-parser
TypeScript icon, indicating that this package has built-in type declarations

0.9.1 • Public • Published

fast-png-parser

npm npm bundle size GitHub GitHub Workflow Status GitHub last commit

Fast, lightweight and memory efficient PNG chunk parser.

Install

npm install --save fast-png-parser

Usage

  • Extract the image width and height.

It should be fast and memory efficient because extractPNG returns immediately just after the IHDR chunk. It must be the first chunk of PNG file so that you can skip all of the rest of chunks.

import { open } from 'node:fs/promises';
import { extractPNG, parsePNG } from 'fast-png-parser';

const fh = await open('test.png', 'r');
const chunks = await extractPNG(fh, { filter: type => type === 'IHDR', maxChunks: 1 });
fh.close();

if (chunks[0]) {
  const ihdr = parsePNG(chunks[0]);
  console.log(ihdr.width, ihdr.height);
}
  • Extract the first tEXt chunk.

It should be fast and memory efficient because extractPNG returns immediately just after the first tEXt chunk. In most cases, tEXt chunks appear before IDAT chunks so that you can skip to read large IDAT chunks.

import { open } from 'node:fs/promises';
import { extractPNG, parsePNG } from 'fast-png-parser';

const fh = await open('test.png', 'r');
const chunks = await extractPNG(fh, { filter: type => type === 'tEXt', maxChunks: 1 });
fh.close();

if (chunks[0]) {
  const text = parsePNG(chunks[0]);
  console.log(text.keyword, text.text);
}
  • CRC check

If you need to check CRC, install crc-32 module and create calcCRC32 function to check CRC.

import { open } from 'node:fs/promises';
import { extractPNG, parsePNG } from 'fast-png-parser';
import CRC32 from 'crc-32';

const calcCRC32 = chunk => CRC32.buf(Buffer.concat([Buffer.from(chunk.type), chunk.data]));

const fh = await open('test.png', 'r');
const chunks = await extractPNG(fh);
fh.close();

console.log(chunks.map(chunk => chunk.crc === calcCRC32(chunk)));

Source code

License

MIT License. See LICENSE file.

Author

Susumu OTA

Package Sidebar

Install

npm i fast-png-parser

Weekly Downloads

0

Version

0.9.1

License

MIT

Unpacked Size

11.8 kB

Total Files

5

Last publish

Collaborators

  • susumuota