node-libpng
Version:
Unofficial bindings for node to libpng.
86 lines • 3.15 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.readPngFileSync = exports.readPngFile = exports.decode = void 0;
const fs_1 = require("fs");
const png_image_1 = require("./png-image");
/**
* Decode a buffer of encoded PNG data into a `PngImage` offering access to the raw image data.
*
* @param buffer The buffer to convert.
*
* @return the decoded PNG as a `PngImage` instance.
*/
function decode(buffer) {
return new png_image_1.PngImage(buffer);
}
exports.decode = decode;
/**
* Invoke `readPngFile` to asynchroneously read a png file into a decoded image.
* For convenience, both Node.js callbacks and Promises are supported.
* If no callback is provided as a second argument, a Promise is returned which will resolve
* with the decoded image.
*
* @param path The path to the file to decode.
* @param callback An optional callback to use instead of a returned Promise. Will be called with
* an error as the first argument or `null` if everything went well, and the decoded
* image as a second argument if no error occured.
* @return A Promise if no callback was provided and `undefined` otherwise.
*/
function readPngFile(path, callback) {
// Check if the user provided a `callback`.
if (typeof callback === "function") {
fs_1.readFile(path, (readError, data) => {
// Call the callback with an error if an error occured.
if (readError) {
callback(readError);
return;
}
// Try to decode the PNG image. Catch any errors that might occur.
let pngImage;
try {
pngImage = new png_image_1.PngImage(data);
}
catch (decodeError) {
callback(decodeError);
return;
}
// If no error occured, call the callback with the decoded image.
callback(null, pngImage);
});
return;
}
// If the user didn't provide a callback, return a Promise which will resolve with the decoded image.
return new Promise((resolve, reject) => {
return fs_1.readFile(path, (readError, data) => {
// Reject if an error occured during read.
if (readError) {
reject(readError);
return;
}
// Try to decode the PNG image. Catch any errors that might occur.
let pngImage;
try {
pngImage = new png_image_1.PngImage(data);
}
catch (decodeError) {
reject(decodeError);
return;
}
// If no error occured, resolve the Promise with the decoded image.
resolve(pngImage);
});
});
}
exports.readPngFile = readPngFile;
/**
* Decode a PNG file synchroneously.
*
* @param path The path to the file to decode.
*
* @return The decoded image.
*/
function readPngFileSync(path) {
return new png_image_1.PngImage(fs_1.readFileSync(path));
}
exports.readPngFileSync = readPngFileSync;
//# sourceMappingURL=decode.js.map