UNPKG

image-js

Version:

Image processing and manipulation in JavaScript

73 lines 2.6 kB
import { Mask } from '../Mask.js'; import { getNodeApiOrThrow } from '../utils/cross_platform.js'; import { encode } from './encode.js'; /** * Asynchronously write an image to the disk. * This method is only implemented for Node.js. * @param path - Path where the image should be written. * @param image - Image to save. * @param options - Encode options. */ export async function write(path, image, options) { const nodeApi = getNodeApiOrThrow('write'); if (typeof path !== 'string') { path = nodeApi.url.fileURLToPath(path); } if (image instanceof Mask) { image = image.convertColor('GREY'); } const toWrite = getDataToWrite(path, image, options, nodeApi); if (options?.recursive) { const dir = nodeApi.path.dirname(path); await nodeApi.fs.promises.mkdir(dir, { recursive: true }); } await nodeApi.fs.promises.writeFile(path, toWrite); } /** * Synchronous version of {@link write}. * This method is only implemented for Node.js. * @param path - Path where the image should be written. * @param image - Image to save. * @param options - Encode options. */ export function writeSync(path, image, options) { const nodeApi = getNodeApiOrThrow('writeSync'); if (typeof path !== 'string') { path = nodeApi.url.fileURLToPath(path); } const toWrite = getDataToWrite(path, image, options, nodeApi); if (options?.recursive) { const dir = nodeApi.path.dirname(path); nodeApi.fs.mkdirSync(dir, { recursive: true }); } nodeApi.fs.writeFileSync(path, toWrite); } /** * Encode the image to the format specified by the file's extension. * @param destinationPath - Image destination. * @param image - Image to save. * @param options - Encode options. * @param nodeApi - Object with Node.js APIs. * @returns Buffer containing the encoded image. */ function getDataToWrite(destinationPath, image, options, nodeApi) { if (!options || !('format' in options)) { const extension = nodeApi.path .extname(destinationPath) .slice(1) .toLowerCase(); if (extension === 'png' || extension === 'jpg' || extension === 'jpeg' || extension === 'bmp') { return encode(image, { ...options, format: extension }); } else { throw new RangeError('image format could not be determined from file extension. Use a supported extension or specify the format option'); } } else { return encode(image, options); } } //# sourceMappingURL=write.js.map