boost-image

Client library for image processing service

Boost Image

Library for working with the Boost Image API service. Allows you to easily optimize, convert and resize images in your JavaScript or TypeScript project.

You can get a free API key in your personal account at https://boost-image.online/profile/api.

Installation

npm install boost-image

or

yarn add boost-image

Usage

Simple Example

import BoostImage from "boost-image";
import { CompressionLevel } from "boost-image/dist/types";

const client = new BoostImage({
  apiKey: "your-api-key",
});

async function processImage() {
  // Create a compression task
  const task = await client.createTask("compress");

  // Upload an image (can be a file, Blob, or URL)
  // and pass processing parameters
  await client.upload(task, "https://example.com/image.jpg", {
    compression_level: CompressionLevel.RECOMMENDED,
  });

  // Process the image
  await client.process(task);

  // Download processed images
  const results = await client.download(task);

  // Work with the result (array of objects with image data)
  if (results.length > 0) {
    const firstResult = results[0];
    console.log("Compressed image size:", firstResult.size);
    console.log("Display URL:", firstResult.url);

    // Use Blob for saving the file
    const blob = firstResult.blob;
    // ...
    // or Buffer in Node.js
    const buffer = firstResult.buffer;
    fs.writeFileSync(outputPath, result.buffer);
    // ...
  }
}

processImage().catch(console.error);

Format Conversion

import { ConvertTo } from "boost-image/dist/types";

const task = await client.createTask("convert");
// Pass conversion parameters during upload
await client.upload(task, imageFile, {
  format: ConvertTo.WEBP,
});
// Process the image
await client.process(task);
// Download the results
const results = await client.download(task);
if (results.length > 0) {
  const convertedImage = results[0];
  console.log("Image URL:", convertedImage.url);
}

Resizing

import { ResizeMode } from "boost-image/dist/types";

const task = await client.createTask("resize");
// Pass resize parameters during upload
await client.upload(task, imageFile, {
  width: 800,
  height: 600,
  resizeMode: ResizeMode.PIXELS,
  maintain_ratio: true,
  no_enlarge_if_smaller: true,
});
// Process the image
await client.process(task);
// Download the results
const results = await client.download(task);
if (results.length > 0) {
  const resizedImage = results[0];
  console.log("New dimensions:", resizedImage.width + "x" + resizedImage.height);
}

Example of Using a Local File (Node.js Only)

import BoostImage from "boost-image";
import { CompressionLevel } from "boost-image/dist/types";

const client = new BoostImage({
  apiKey: "your-api-key",
});

async function processLocalImage() {
  try {
    // Create a compression task
    const task = await client.createTask("compress");

    // Path to local file
    const localFilePath = "/Users/username/Images/photo.jpg";

    // Upload the image from a local file
    await client.upload(task, localFilePath, {
      compression_level: CompressionLevel.RECOMMENDED,
    });

    // Process the image
    await client.process(task);

    // Download the results
    const results = await client.download(task);

    if (results.length > 0) {
      console.log("Processing complete!");
      console.log("Compressed image size:", results[0].size, "bytes");

      // The file can be saved using fs
      const fs = require("fs");
      fs.writeFileSync(
        "/Users/username/Images/compressed_photo.jpg",
        results[0].buffer
      );
    }
  } catch (error) {
    console.error("Error processing image:", error);
  }
}

processLocalImage();

Initialization with Settings

import BoostImage from "boost-image";

// Create a client with additional settings
const client = new BoostImage({
  apiKey: "your-api-key",
});

Processing Multiple Images

// Example of processing multiple images
async function processMultipleImages(imageUrls) {
  // Create a task for batch processing
  const task = await client.createTask("compress");
  
  // Upload all images
  for (const url of imageUrls) {
    await client.upload(task, url, {
      compression_level: CompressionLevel.HIGH,
    });
  }
  
  // Process the images
  await client.process(task);
  
  // Download the results
  const results = await client.download(task);
  console.log(`Successfully processed ${results.length} images`);
  
  return results;
}

// Example call with an array of URLs
processMultipleImages([
  "https://example.com/image1.jpg",
  "https://example.com/image2.jpg",
  // ... add more images
])
  .then(results => console.log("Processing complete!"))
  .catch(error => console.error("Error:", error));

Processing a Folder with Images (Node.js Only)

The library provides a convenient processFolder method for processing all images in a specified directory while preserving the folder structure. This method is only available in the Node.js environment.

const path = require("path");
const BoostImage = require("boost-image").default;
const { ToolName, CompressionLevel, ConvertTo, ResizeMode } = require("boost-image/dist/types");
const dotenv = require("dotenv");

// Load environment variables from .env file
dotenv.config();

// Initialize the client
const client = new BoostImage({
  apiKey: process.env.API_KEY,
});

// Paths to directories
const imagesDir = path.join(__dirname, "images");
const processedDir = path.join(__dirname, "images-processed");

async function main() {
  // Process all images in the directory and save the results
  // The method itself creates a task of the required type
  const results = await client.processFolder(
    ToolName.COMPRESS,
    imagesDir, 
    processedDir, 
    {
      compression_level: CompressionLevel.LOW,
    }
  );
  
  // Get information about results and statistics
  const { list, statistics } = results;
  
  // Output statistics
  console.log("Total number of files:", statistics.totalFiles);
  console.log("Successfully processed files:", statistics.processedFiles);
  console.log("Size before processing:", client.formatFileSize(statistics.sizeBefore));
  console.log("Size after processing:", client.formatFileSize(statistics.sizeAfter));
  console.log("Compression ratio:", statistics.compressionRatio);
  console.log("Saved:", client.formatFileSize(statistics.saved));
  
  if (statistics.errors.length > 0) {
    console.log("Number of errors:", statistics.errors.length);
  }
}

// Run the main function
main().catch(console.error);

Examples of using the processFolder method for different types of operations:

// Image compression
const compressResults = await client.processFolder(
  ToolName.COMPRESS,
  imagesDir, 
  processedDir, 
  { 
    compression_level: CompressionLevel.RECOMMENDED,
    rotate: 0  // optional
  }
);

// Converting images to WebP
const convertResults = await client.processFolder(
  ToolName.CONVERT,
  imagesDir, 
  processedDir, 
  { 
    convert_to: ConvertTo.WEBP,
    compression_level: CompressionLevel.LOW  // optional
  }
);

// Resizing images
const resizeResults = await client.processFolder(
  ToolName.RESIZE,
  imagesDir, 
  processedDir, 
  { 
    resize_mode: ResizeMode.PIXELS,
    pixels_width: 800,
    pixels_height: 600,
    maintain_ratio: true,
    no_enlarge_if_smaller: true
  }
);

// Cropping images
const cropResults = await client.processFolder(
  ToolName.CROP,
  imagesDir, 
  processedDir, 
  { 
    width: 500,
    height: 300,
    x: 100,  // optional
    y: 100   // optional
  }
);

The processFolder method automatically performs the following actions:

  • Finds all images in the specified directory (including subdirectories)
  • Splits large sets of files into batches for efficient processing
  • Uploads, processes, and downloads each batch of images
  • Saves processed images along the same relative paths in the destination directory
  • Provides detailed statistics about processing results

This method significantly simplifies working with large sets of images, preserving the folder structure and providing complete statistics on processing results.

API

Constructor

const client = new BoostImage(config);

Parameters:

  • config: Configuration object
    • apiKey: Your API key (required)
    • baseURL: API URL (optional, default is https://api.boostimage.com/v1)

Methods

createTask(type)

Creates a new task for image processing.

  • type: Task type ('compress', 'convert', 'resize')
  • Returns: Promise with a task object

upload(task, source, params, onProgress)

Uploads an image for processing.

  • task: Task object
  • source: Can be one of the following:
    • File or Blob object - for use in browser
    • URL string (starts with http:// or https://) - for loading from a remote resource
    • String with a local path (starts with / or contains a disk in Windows) - for use in Node.js
  • params: Parameters for image processing
  • onProgress: Callback function for tracking upload progress (optional)
  • Returns: Promise with an updated task object

Important: Using local file paths only works in a Node.js environment and is not available in the browser.

process(task)

Processes uploaded images.

  • task: Task object with information about files and processing parameters
  • Returns: Promise with processing result

processFolder(toolName, inputDir, outputDir, options)

Processes all images in the specified directory and saves results to the destination directory, preserving the folder structure. Only available in the Node.js environment.

  • toolName: Operation type from the ToolName enumeration (compress, convert, resize, rotate, crop)
  • inputDir: String with path to directory with source images
  • outputDir: String with path to directory for saving processed images
  • options: Object with processing parameters, depending on the operation type:
    • For ToolName.COMPRESS: object of type CompressParams
    • For ToolName.CONVERT: object of type ConvertParams
    • For ToolName.RESIZE: object of type ResizeParams
    • For ToolName.CROP: object of type CropParams
  • Returns: Promise with an object containing:
    • list: Array of processed images (objects of type ImageType)
    • statistics: Statistics object:
      • totalFiles: Total number of files found
      • processedFiles: Number of successfully processed files
      • sizeBefore: Size before compression in bytes
      • sizeAfter: Size after compression in bytes
      • compressionRatio: Compression ratio in percentage
      • saved: Saved size in bytes
      • errors: Array with error descriptions

formatFileSize(bytes)

Helper method for formatting file size in human-readable format.

  • bytes: Size in bytes
  • Returns: String with formatted size (e.g., "10.5 MB")

download(task)

Downloads processed images.

  • task: Task object
  • Returns: Promise with an array of objects of type ImageType

Enumerations

ToolName

Types of operations available for image processing:

enum ToolName {
  ROTATE = "rotate",   // Image rotation
  CONVERT = "convert", // Conversion to another format
  COMPRESS = "compress", // Image compression
  CROP = "crop",     // Image cropping
  RESIZE = "resize", // Resizing
}

CompressionLevel

enum CompressionLevel {
  EXTREME = "extreme",
  RECOMMENDED = "recommended",
  LOW = "low",
}

ConvertTo

enum ConvertTo {
  WEBP = "webp",
  JPG = "jpg",
  PNG = "png",
  AVIF = "avif",
}

ResizeMode

enum ResizeMode {
  PIXELS = "pixels",
  PERCENTAGE = "percentage",
}

ImageType Object Structure

interface ImageType {
  id?: string; // Image ID
  original_id?: string; // Original image ID
  task_id: string; // Task ID
  original_filename: string; // Original file name
  server_filename: string; // File name on server
  size_before?: number; // Size before processing in bytes
  size: number; // Size after processing in bytes
  width: number; // Image width
  height: number; // Image height
  type: string; // Image type (original/processed)
  extension: string; // File extension
  mimetype: string; // File MIME type
  created_at?: Date | string; // Creation date
  status: string; // Processing status
  blob?: Blob; // Blob object with image data (for browser)
  url?: string; // URL for displaying the image (for browser)
  buffer?: Buffer; // Buffer with image data (for Node.js)
}

Operation Parameters

Parameters for different types of operations:

// Parameters for resize operation
type ResizeParams = {
  resize_mode: ResizeMode;         // Resize mode (pixels or percentage)
  pixels_width?: number;           // Width in pixels (for pixels mode)
  pixels_height?: number;          // Height in pixels (for pixels mode)
  percentage?: number;             // Percentage of original size (for percentage mode)
  maintain_ratio: boolean;         // Maintain aspect ratio
  no_enlarge_if_smaller: boolean;  // Do not enlarge image if it's smaller than the specified size
};

// Parameters for crop operation
type CropParams = {
  width: number;   // Crop width
  height: number;  // Crop height
  x?: number;      // X coordinate of the starting point for cropping
  y?: number;      // Y coordinate of the starting point for cropping
};

// Parameters for compression operation
type CompressParams = {
  compression_level: CompressionLevel;  // Compression level
  rotate?: number | string;            // Rotation angle (optional)
};

// Parameters for format conversion operation
type ConvertParams = {
  convert_to: ConvertTo;                // Format for conversion
  compression_level?: CompressionLevel; // Compression level (optional)
};

License

MIT