### Install pngjs3 using npm or yarn Source: https://github.com/jimp-dev/pngjs3/blob/master/README.md Demonstrates how to install the pngjs3 package using either npm or yarn package managers. ```bash $ npm install pngjs3 --save ``` ```bash $ yarn add pngjs3 ``` -------------------------------- ### PNG Parsing Example Source: https://github.com/jimp-dev/pngjs3/blob/master/README.md Demonstrates how to parse PNG image data using the `png.parse` method. It includes an optional callback for handling errors and parsed data. ```javascript new PNG({ filterType: 4 }).parse(imageData, function (error, data) { console.log(error, data); }); ``` -------------------------------- ### Async PNG Processing Example Source: https://github.com/jimp-dev/pngjs3/blob/master/README.md An example showcasing the asynchronous API of pngjs3 to read a PNG file, modify its pixel data (invert colors and reduce opacity), and then write the modified image to a new file. It uses Node.js streams for reading and writing. ```javascript import fs from 'fs'; import PNG from 'pngjs3'; 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')); }); ``` -------------------------------- ### PNG Packing API Source: https://github.com/jimp-dev/pngjs3/blob/master/README.md Starts converting image data into a PNG file stream. ```APIDOC ## POST /png/pack ### Description Starts converting data to PNG file Stream. Returns `this` for method chaining. ### Method POST ### Endpoint /png/pack ### Parameters #### Request Body - **imageData** (object) - The image data to pack into PNG format. ### Request Example ```js const png = new PNG({ width: 10, height: 10 }); // ... populate png with pixel data ... png.pack().pipe(fs.createWriteStream('output.png')); ``` ### Response #### Success Response (200) - **stream** (Stream) - A stream representing the packed PNG file. #### Response Example (Response is a stream, not a JSON object) ``` -------------------------------- ### Pack PNG with Alpha Removal (RGBA to RGB) - PNGJS3 Source: https://github.com/jimp-dev/pngjs3/blob/master/README.md Shows how to pack a PNG image while removing the alpha channel, converting RGBA to RGB. This process requires a background color to correctly blend transparent pixels. The example flattens the image against a green background. ```javascript import fs from 'fs'; import PNG from 'pngjs3'; 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')); }); ``` -------------------------------- ### PNG Instance Configuration Options Source: https://github.com/jimp-dev/pngjs3/blob/master/README.md Describes the various options available when creating a new PNG instance. ```APIDOC ## PNG Instance Options ### Description Configuration options for creating a new PNG instance. ### Options - **`id`** (string) - Optional identifier for tracking the object in memory. - **`width`** (number) - Width of the PNG, used when creating from scratch. - **`height`** (number) - Height of the PNG, used when creating from scratch. - **`checkCRC`** (boolean) - Whether to strictly check checksums in the source stream (default: `true`). - **`deflateChunkSize`** (number) - Chunk size for deflating data chunks. Must be a power of 2, >= 256 and <= 32*1024 (default: 32 kB). - **`deflateLevel`** (number) - Compression level for deflate (default: 9). - **`deflateStrategy`** (number) - Compression strategy for deflate (default: 3). - **`deflateFactory`** (function) - Deflate stream factory (default: `zlib.createDeflate`). - **`filterType`** (number | number[]) - PNG filtering method for scanlines (default: -1 => auto, accepts array of numbers 0-4). - **`colorType`** (number) - The output color type (0: grayscale, 2: color, 4: grayscale & alpha, 6: color & alpha). Default is 6. - **`inputColorType`** (number) - The input color type (default: 6 for RGBA). - **`bitDepth`** (number) - The bit depth of the output, 8 or 16 bits. Input data is expected to have this bit depth. 16-bit data is expected in system endianness (default: 8). - **`inputHasAlpha`** (boolean) - Whether the input bitmap has 4 bytes per pixel (RGB + alpha) or 3 (RGB - no alpha). - **`bgColor`** (object) - Background color object with `red`, `green`, `blue` values (0-255). Used when packing a PNG without alpha (default: { red: 255, green: 255, blue: 255 }). - **`skipRescale`** (boolean) - If true, skips rescaling to an 8-bit bitmap, retaining 16-bit data structure. - **`initGrayscaleData`** (boolean) - If true, initializes grayscale conversion for `grayscaleData` call. - **`initPropData`** (boolean | object) - If true or an object, initializes `propData` for `initPropData` call. ### Example ```js const png = new PNG({ width: 100, height: 150, filterType: 4, bitDepth: 16 }); ``` ``` -------------------------------- ### Image Loading and Comparison Test Suite (JavaScript) Source: https://github.com/jimp-dev/pngjs3/blob/master/test/index.html This JavaScript code sets up a test suite to compare images for equality. It asynchronously loads images, performs comparisons using an `imagediff` library (assumed), and updates the UI to indicate test success or failure. It handles different tolerance levels based on image filenames. ```JavaScript function waitForImages(images, fnCallback) { setTimeout(function () { for (var i = 0; i < images.length; i++) { if (!images[i].complete) { waitForImages(images, fnCallback); return; } } fnCallback(); }, 10); } window.isFinished = function () { return testCount && testsDone === testCount; }; window.results = []; var testLines = document.getElementsByClassName('testline'); var testCount = testLines.length, testsDone = 0; for (var i = 0; i < testLines.length; i++) { var testLine = testLines[i]; var inImage = testLine.getElementsByClassName('inimage')[0]; var asyncImage = testLine.getElementsByClassName('asyncimage')[0]; var syncImage = testLine.getElementsByClassName('syncimage')[0]; waitForImages( [inImage, asyncImage, syncImage], function (inImage, asyncImage, syncImage, testLine) { var success = true; console.log('testing ' + inImage.src); var tolerance; if (inImage.src.match(/16\.png/)) { tolerance = 2; // phantomjs uses a different scaling method. } else { tolerance = 0; } if (asyncImage.height === 0 || syncImage.height === 0) { success = false; } else { var equal = imagediff.equal(inImage, asyncImage, tolerance); if (!equal) { success = false; } equal = imagediff.equal(inImage, syncImage, tolerance); if (!equal) { success = false; } } if (!success) { testLine.className = testLine.className + ' failure'; } else { testLine.className = testLine.className + ' success'; } results.push({ name: inImage.src.replace(/\.png$/, '').replace(/^.*\//, ''), success: success, }); testsDone++; }.bind(null, inImage, asyncImage, syncImage, testLine), ); } ``` -------------------------------- ### Polyfill for Function.prototype.bind (JavaScript) Source: https://github.com/jimp-dev/pngjs3/blob/master/test/index.html Provides a backward-compatible implementation of the `bind` method for `Function.prototype` if it's not natively available. This ensures consistent behavior across different JavaScript environments. ```JavaScript if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== 'function') { throw new TypeError( 'Function.prototype.bind - what is trying to be bound is not callable', ); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () {}, fBound = function () { return fToBind.apply( this instanceof fNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments)), ); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }; } ``` -------------------------------- ### PNG.js API Documentation Source: https://github.com/jimp-dev/pngjs3/blob/master/README.md This section details the core properties and methods of the PNG.js library for handling PNG image data. ```APIDOC ## PNG Class Properties and Methods ### Property: adjustGamma() **Description**: Helper that adjusts image gamma to be corrected. Note that it is not 100% reliable with transparent colours. Compares 100% with Chrome on 8-bit images and below. **Method**: N/A (Instance method) **Endpoint**: N/A ### Property: width **Description**: Width of the image in pixels. **Method**: N/A **Endpoint**: N/A ### Property: height **Description**: Height of the image in pixels. **Method**: N/A **Endpoint**: N/A ### Property: shape **Description**: Object containing the `height` and `width` of the image. **Method**: N/A **Endpoint**: N/A ### Property: data **Description**: Buffer of image pixel data. Each pixel consists of 4 bytes: R, G, B, A (opacity). **Method**: N/A **Endpoint**: N/A ### Property: gamma **Description**: Gamma of the image (0 if not specified). **Method**: N/A **Endpoint**: N/A ## Serializing and Deserializing ### serialize() **Description**: Returns a plain serializable object representation of the PNG image. **Method**: Instance method **Endpoint**: N/A ### static deserialize(data) **Description**: Recreates a PNG object from serialized data. **Method**: Static method **Endpoint**: N/A **Parameters**: #### Path Parameters - None #### Query Parameters - None #### Request Body - **data** (object) - Serialized PNG data. **Request Example**: ```json { "example": "myPNG.serialize()" } ``` ### Response #### Success Response (200) - **output** (object) - Serialized PNG data or recreated PNG object. **Response Example**: ```json { "example": "PNG.deserialize(data2store)" } ``` ## Packing a PNG and removing alpha (RGBA to RGB) **Description**: Packs a PNG image, optionally removing the alpha channel and converting RGBA to RGB. By default, it flattens against a white background. This can be overridden with `bgColor` option. **Method**: Instance method (`pack()`) **Endpoint**: N/A **Parameters**: #### Path Parameters - None #### Query Parameters - None #### Request Body - **options** (object) - Optional configuration for packing. - **colorType** (number) - The color type to use (e.g., 2 for RGB). - **bgColor** (object) - Background color for alpha conversion. - **red** (number) - **green** (number) - **blue** (number) **Request Example**: ```js 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 Source: https://github.com/jimp-dev/pngjs3/blob/master/README.md Provides synchronous methods for reading and writing PNG files. ```APIDOC ## Sync API ### static read(buffer) **Description**: Takes a buffer and returns a PNG image object with metadata and pixel data. **Method**: Static method **Endpoint**: N/A **Parameters**: #### Path Parameters - None #### Query Parameters - None #### Request Body - **buffer** (Buffer) - The buffer containing PNG data. **Request Example**: ```js const data = fs.readFileSync('in.png'); const png = PNGSync.read(data); ``` ### static write(png, options) **Description**: Takes a PNG image object and returns a buffer. Options can be provided to control the output format. **Method**: Static method **Endpoint**: N/A **Parameters**: #### Path Parameters - None #### Query Parameters - None #### Request Body - **png** (object) - The PNG image object. - **options** (object) - Optional configuration for writing. - **colorType** (number) - The color type for the output buffer. **Request Example**: ```js const png = PNGSync.read(data); const options = { colorType: 6 }; const buffer = PNGSync.write(png, options); ``` ### adjustGamma(png) **Description**: Adjusts the gamma of a synchronous PNG image object. Similar to the async `adjustGamma` method. **Method**: Static method **Endpoint**: N/A **Parameters**: #### Path Parameters - None #### Query Parameters - None #### Request Body - **png** (object) - The PNG image object to adjust. **Request Example**: ```js const png = PNGSync.read(data); adjustGamma(png); ``` ``` -------------------------------- ### Pixel Manipulation with bitblt Source: https://github.com/jimp-dev/pngjs3/blob/master/README.md Shows how to copy a rectangular region of pixels from one PNG image to another using the `bitblt` helper function. This is useful for image manipulation tasks. ```javascript const dst = new PNG({ width: 100, height: 50 }); fs.createReadStream('in.png') .pipe(new PNG()) .on('parsed', function () { this.bitblt({ dst, srcX: 0, srcY: 0, width: 100, height: 150, deltaX: 0, deltaY: 0, }); dst.pack().pipe(fs.createWriteStream('out.png')); }); ``` -------------------------------- ### Image Manipulation API (bitblt) Source: https://github.com/jimp-dev/pngjs3/blob/master/README.md Helper function for image manipulation, copies a rectangle of pixels from one image to another. ```APIDOC ## POST /image/bitblt ### Description Helper for image manipulation, copies a rectangle of pixels from current (i.e. the source) image (`srcX`, `srcY`, `width`, `height`) to `dst` image (at `deltaX`, `deltaY`). Returns `this` for method chaining. ### Method POST ### Endpoint /image/bitblt ### Parameters #### Request Body - **dst** (PNG) - The destination PNG object to copy pixels to. - **srcX** (number) - The starting x-coordinate of the source rectangle. - **srcY** (number) - The starting y-coordinate of the source rectangle. - **width** (number) - The width of the rectangle to copy. - **height** (number) - The height of the rectangle to copy. - **deltaX** (number) - The starting x-coordinate in the destination image. - **deltaY** (number) - The starting y-coordinate in the destination image. ### Request Example ```js const dst = new PNG({ width: 100, height: 50 }); fs.createReadStream('in.png') .pipe(new PNG()) .on('parsed', function () { this.bitblt({ dst: dst, srcX: 0, srcY: 0, width: 100, height: 150, deltaX: 0, deltaY: 0, }); dst.pack().pipe(fs.createWriteStream('out.png')); }); ``` ### Response #### Success Response (200) - **status** (string) - Indicates successful operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Serialize and Deserialize PNG Data - PNGJS3 Source: https://github.com/jimp-dev/pngjs3/blob/master/README.md Demonstrates how to serialize a PNG object into a plain data structure suitable for state management libraries like Redux, and then deserialize it back into a PNG object. The deserialized object shares the same underlying data storage but is a new instance. ```javascript import PNG from 'pngjs3'; myPNG = new PNG(); // ... other operations const data2store = myPNG.serialize(); // ... store data2store const myRecreatedObject = PNG.deserialize(data2store); console.log(myRecreatedObject !== myPNG, 'A new object has been created'); console.log(myRecreatedObject.storage === myPNG.storage, 'But the storage (i.e. data) is the same'); ``` -------------------------------- ### PNG Parsing API Source: https://github.com/jimp-dev/pngjs3/blob/master/README.md Provides methods for parsing PNG image data from various sources. ```APIDOC ## POST /png/parse ### Description 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. ### Method POST ### Endpoint /png/parse ### Parameters #### Request Body - **data** (String | Buffer) - The PNG image data to parse. - **callback** (function) - Optional callback function to handle parsing results. ### Request Example ```js new PNG({ filterType: 4 }).parse(imageData, function (error, data) { console.log(error, data); }); ``` ### Response #### Success Response (200) - **data** (object) - Parsed PNG image data. #### Response Example ```json { "error": null, "data": { "width": 100, "height": 50, "palette": [], "bitDepth": 8, "colorType": 6 } } ``` ``` -------------------------------- ### PNG Events Source: https://github.com/jimp-dev/pngjs3/blob/master/README.md Describes the events emitted by the PNG parser during processing. ```APIDOC ## PNG Events ### Description Events emitted by the PNG parser to signal parsing progress and status. ### Event: "metadata" `function(metadata) { }` Image's header has been parsed. `metadata` contains: - `width` (number): Image width in pixels. - `height` (number): Image height in pixels. - `palette` (boolean): Indicates if the image uses a palette. - `color` (boolean): Indicates if the image is not grayscale. - `alpha` (boolean): Indicates if the image contains an alpha channel. - `interlace` (boolean): Indicates if the image is interlaced. ### Event: "parsed" `function(data) { }` Input image has been completely parsed. `data` is complete and ready for modification. ### Event: "error" `function(error) { }` Emitted when an error occurs during parsing. ``` -------------------------------- ### Write PNG Synchronously - PNGJS3 Source: https://github.com/jimp-dev/pngjs3/blob/master/README.md Writes a PNG image object to a Buffer synchronously using the PNGJS3 sync API. Options can be provided to control the output, such as the color type. The resulting buffer can then be saved to a file. ```javascript import { sync as PNGSync } from 'pngjs3'; const data = fs.readFileSync('in.png'); const png = PNGSync.read(data); const options = { colorType: 6 }; const buffer = PNGSync.write(png, options); fs.writeFileSync('out.png', buffer); ``` -------------------------------- ### Read PNG Buffer Synchronously - PNGJS3 Source: https://github.com/jimp-dev/pngjs3/blob/master/README.md Reads a PNG image from a Buffer synchronously using the PNGJS3 sync API. The returned PNG object contains image metadata and pixel data. ```javascript import { sync as PNGSync } from 'pngjs3'; const data = fs.readFileSync('in.png'); const png = PNGSync.read(data); ``` -------------------------------- ### Adjust Gamma Async - PNGJS3 Source: https://github.com/jimp-dev/pngjs3/blob/master/README.md Reads a PNG file, adjusts its gamma to 0 (effectively removing gamma correction), and saves the modified image. This method is generally reliable for 8-bit images but may have minor discrepancies with transparent colors or specific browsers. ```javascript fs.createReadStream('in.png') .pipe(new PNG()) .on('parsed', function () { this.adjustGamma(); this.pack().pipe(fs.createWriteStream('out.png')); }); ``` -------------------------------- ### Adjust Gamma Synchronously - PNGJS3 Source: https://github.com/jimp-dev/pngjs3/blob/master/README.md Adjusts the gamma of a PNG image object synchronously. This function modifies the image data in place. ```javascript import { sync as PNGSync, adjustGamma } from 'pngjs3'; const data = fs.readFileSync('in.png'); const png = PNGSync.read(data); adjustGamma(png); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.