The AioImageProcessor class is a powerful tool for manipulating and processing images. It allows you to resize, convert, add watermarks, and set metadata for images. This class extends AioFileOperation, providing a robust foundation for file-related operations.

  • Image Conversion: Convert images between various formats (JPEG, PNG, WebP, TIFF, GIF).
  • Resizing: Resize images while maintaining aspect ratio or crop to a square.
  • Watermarking: Add watermarks to images with customizable position and opacity.
  • Metadata: Set EXIF metadata such as description, author, copyright, and keywords.
  • Optimization: Optimize images for web use by reducing file size.
  • Customizable Settings: Configure default settings for resizing, watermarking, and metadata.
  • Error Handling: Robust error handling for unsupported formats and missing source files.

npm install sharp

import { AioImageProcessor } from './path/to/AioImageProcessor';

async function processImage() {
const imageProcessor = new AioImageProcessor();
await imageProcessor
.img('/path/to/your/image.jpg')
.toImg('/path/to/output/image.png', { resize: true, maxWidth: 800, watermark: true });
}

processImage().catch(console.error);

import { AioImageProcessor } from './path/to/AioImageProcessor';

async function processImage() {
const imageProcessor = new AioImageProcessor();
imageProcessor.settings = {
maxWidth: 600,
metadata: {
description: 'Custom description',
author: 'Custom Author',
},
watermark: {
opacity: 0.7,
position: 'bottom',
},
};
await imageProcessor
.img('/path/to/your/image.jpg')
.toImg('webp', { resize: true, watermark: true });
}

processImage().catch(console.error);

import { AioImageProcessor } from './path/to/AioImageProcessor';

async function processImage() {
const imageProcessor = new AioImageProcessor();
imageProcessor.metadata = {
description: 'New description',
author: 'New Author',
copyright: '© 2024 New Author',
keywords: ['new', 'image', 'metadata'],
};
await imageProcessor
.img('/path/to/your/image.jpg')
.toImg('/path/to/output/image.jpg', { resize: true, maxWidth: 800 });
}

processImage().catch(console.error);

import { AioImageProcessor } from './path/to/AioImageProcessor';

async function processImage() {
const imageProcessor = new AioImageProcessor();
imageProcessor.watermark = {
path: '/path/to/new/watermark.png',
opacity: 0.8,
};
await imageProcessor
.img('/path/to/your/image.jpg')
.toImg('/path/to/output/image.jpg', { resize: true, maxWidth: 800, watermark: true });
}

processImage().catch(console.error);

Hierarchy (View Summary)

Constructors

  • Creates an instance of AioImageProcessor. Initializes the image processor with default settings and resolves the template directory path.

    Parameters

    • Optionalfilepath: string

      Optional. The initial filepath for the image to be processed.

    Returns AioImageProcessor


    const imageProcessor = new AioImageProcessor();
    const imageProcessor = new AioImageProcessor('/path/to/your/image.jpg');

Properties

_root: string
_settings: any
_Sharp: typeof sharp = sharp
ext: string = ''
filename: string = ''
filepath: undefined | string = ''
outputPath: string = ''

Accessors

  • get content(): any
  • Returns any

  • set content(value: any): void
  • Parameters

    • value: any

    Returns void

  • get metadata(): ImageMetadata
  • Gets the current metadata settings.

    Returns ImageMetadata

    • The current metadata settings object.
  • set metadata(value: ImageMetadata): void
  • Sets the metadata for the image processor. Merges the provided metadata with the existing metadata.

    Parameters

    Returns void


    imageProcessor.metadata = { description: 'New description', author: 'New Author' };
  • get settings(): any
  • Gets the current settings of the image processor.

    Returns any

    • The current settings object.
  • set settings(value: any): void
  • Sets the settings for the image processor. Merges the provided settings with the existing settings.

    Parameters

    • value: any

      The new settings to apply.

    Returns void


    imageProcessor.settings = { maxWidth: 800, watermark: { opacity: 0.5 } };
  • get watermark(): any
  • Gets the current watermark settings.

    Returns any

    • The current watermark settings object.
  • set watermark(value: any): void
  • Sets the watermark settings for the image processor. Merges the provided watermark settings with the existing watermark settings.

    Parameters

    • value: any

      The new watermark settings to apply.

    Returns void


    imageProcessor.watermark = { path: '/path/to/new/watermark.png', opacity: 0.8 };

Methods

  • Private

    Builds the output path for the converted image.

    Parameters

    • pathOrFormat: string

      The output path or format. If only format is provided, the output will be in the same directory as the source.

    • suffix: string

      The suffix to add to the output filename.

    Returns string

    • The full output path.

    this._buildOutputPath('/path/to/output/image.jpg', '_resized');
  • Extracts the file extension from a given filepath and returns it in lowercase.

    Parameters

    • filepath: string

      The path of the file.

    Returns string

    The file extension in lowercase.


    _getExtension('/path/to/my/file.txt') // returns '.txt'
  • Returns the filename without the extension from a given filepath.

    Parameters

    • filepath: string

      The filepath to extract the filename from.

    Returns string

    The filename without the extension.


    _getFilename('/path/to/my/file.txt') // returns 'file'
  • Resizes the image based on the maximum width, maintaining aspect ratio.

    Parameters

    • maxWidth: number

      The maximum width for the resized image.

    • metadataSize: { height: number; width: number }

      The metadata containing the original width and height.

    Returns { height: number; width: number }

    • The new width and height of the image.

    this._resizeByMaxWidth(800, { width: 1200, height: 800 });

    this._resizeByMaxWidth(800, { width: 600, height: 400 });
  • Sets the EXIF metadata for an image. This function takes image metadata and formats it into an EXIF-compatible structure. It supports setting fields like ImageDescription, Artist, Copyright, and more.

    Parameters

    • metadata: ImageMetadata

      The metadata to set, including description, author, copyright, origin, and keywords.

    Returns any

    • The EXIF data object or undefined if no metadata is provided.

    this._setExifMetadata({ description: 'My Image', author: 'John Doe', copyright: '© 2023 John Doe' });

    this._setExifMetadata(undefined);
  • Sets the watermark on the image.

    Parameters

    • converter: Sharp

      The sharp instance for the image.

    Returns Promise<void>

    • A promise that resolves when the watermark is applied.

    await this._setMetadata(converter);
  • Sets the source image file for processing. This method initializes the image processing pipeline by setting the source file path and validating its format.

    Parameters

    • filepath: string

      The path to the source image file.

    Returns this

    • Returns the current instance of AioImageProcessor for method chaining.
    • Throws an error if the provided file format is not supported.

    imageProcessor.img('/path/to/your/image.jpg');
  • Checks if a directory exists. If it doesn't, it creates the directory and any necessary parent directories.

    Parameters

    • dir: string

      The path of the directory to check or create.

    Returns Promise<void>

    • A promise that resolves when the directory exists or has been created.
    • Throws an error if there's a problem creating the directory.

    const fileOp = new AioFileOperation();
    await fileOp.isDirectoryExists('/path/to/new/directory');
    // If '/path/to/new/directory' doesn't exist, it will be created.
  • Opens a file at the specified path and returns a file handle.

    Parameters

    • filePath: string

      The path of the file to open.

    Returns Promise<FileHandle>

    • A promise that resolves to a FileHandle object for the opened file.
    • Throws an error if the file cannot be opened.

    const fileOp = new AioFileOperation();
    const fileHandle = await fileOp.open('/path/to/file.txt');
  • Reads a file synchronously and returns its content as a string.

    Parameters

    • path: string

      The path to the file to be read.

    Returns Promise<string>

    • A promise that resolves to the content of the file as a string. *

    const fileOp = new AioFileOperation();
    const lines = await fileOp.read('/path/to/large/file.txt');
    console.log(lines); // Output: ['Line 1', 'Line 2', 'Line 3', ...]
  • Removes a file if it exists.

    Parameters

    • filePath: string

      The path to the file to be removed.

    Returns Promise<void>

    • A promise that resolves when the file has been removed. *

    const fileOp = new AioFileOperation();
    await fileOp.remove('/path/to/large/file.txt');
  • Reads a file line by line and returns an array of strings, where each string is a line from the file.

    This method opens a file, reads it line by line, and stores each line as a separate string in an array. It uses an asynchronous iterator to efficiently handle large files without loading the entire content into memory at once.

    Parameters

    • filePath: string

      The path to the file to be scanned.

    Returns Promise<string[]>

    • A promise that resolves to an array of strings, where each string is a line from the file.

    const fileOp = new AioFileOperation();
    const lines = await fileOp.scan('/path/to/large/file.txt');
    console.log(lines); // Output: ['Line 1', 'Line 2', 'Line 3', ...]
  • Searches for files within a specified directory, optionally filtering by file extension.

    This method recursively scans a directory and its subdirectories for files. It can filter the results based on a specified file extension or an array of extensions. If no extension is provided, it returns all files. It also has an option to include directories in the results.

    Parameters

    • directory: string

      The path to the directory to search.

    • ext: undefined | string | string[]

      A single file extension or an array of file extensions to filter by. If undefined, no extension filtering is applied.

    • OptionalshowDir: boolean = false

      If true, directories will be included in the results. Defaults to false.

    Returns Promise<undefined | Dirent[]>

    • A promise that resolves to an array of Dirent objects representing the found files.
    • Throws an error if there is a problem accessing the directory, except for 'ENOENT' errors.

    const fileOp = new AioFileOperation();
    // Search for all .txt files in the 'mydir' directory
    const txtFiles = await fileOp.search('mydir', '.txt');
    // Search for all .txt and .md files in the 'mydir' directory
    const txtAndMdFiles = await fileOp.search('mydir', ['.txt', '.md']);
    // Search for all files and directories in the 'mydir' directory
    const allFilesAndDirs = await fileOp.search('mydir', undefined, true);
  • Converts the image to the specified format and applies various options.

    Parameters

    • pathOrFormat: undefined | string

      The output path or the desired format (e.g., 'jpg', 'png'). If only format is provided, the output will be in the same directory as the source.

    • options: ImageOptions = {}

      Options for image processing, including format-specific options, resizing, watermark, etc.

    Returns Promise<undefined | AioImageProcessor>

    • A promise that resolves to the AioImageProcessor instance or undefined if an error occurs.
    • Throws an error if the source image path is not set or if the output format is the same as the input format without optimization.

    await imageProcessor.toImg('/path/to/output/image.jpg', { resize: true, maxWidth: 800, watermark: true });

    await imageProcessor.toImg('png', { resize: true, maxWidth: 800, watermark: true });
  • Writes an array of strings to a file, overwriting any existing content.

    Parameters

    • outputFilePath: string

      The path to the file to be written.

    • content: string[]

      The array of strings to be written to the file. *

    Returns Promise<void>


    const fileOp = new AioFileOperation();
    const dataText = ['Line 1', 'Line 2', 'Line 3', ...]
    const lines = await fileOp.write('/path/to/large/file.txt', dataText);