npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@bernierllc/image-processor

v1.2.2

Published

Image processing utilities for resizing, cropping, format conversion, and optimization with social media aspect ratios

Readme

@bernierllc/image-processor

Image processing utilities for resizing, cropping, format conversion, and optimization with built-in support for social media aspect ratios.

Installation

npm install @bernierllc/image-processor

Features

  • Image Transformations: Resize, crop, and optimize images
  • Format Conversion: Convert between JPEG, PNG, WebP, and AVIF
  • Social Media Presets: Built-in aspect ratios for Instagram, Twitter, Facebook, LinkedIn, and YouTube
  • Thumbnail Generation: Create square thumbnails from any image
  • Quality Optimization: Reduce file size while maintaining visual quality
  • Metadata Extraction: Retrieve image dimensions, format, and properties
  • Logger Integration: Built-in logging with @bernierllc/logger
  • Type-Safe: Full TypeScript support with strict typing

Usage

Basic Usage

import { ImageProcessor } from '@bernierllc/image-processor';
import fs from 'fs';

const processor = new ImageProcessor();

// Read an image
const imageBuffer = fs.readFileSync('photo.jpg');

// Resize image
const resized = await processor.resize(imageBuffer, {
  width: 800,
  height: 600
});

if (resized.success) {
  fs.writeFileSync('photo-resized.jpg', resized.data!);
  console.log('Dimensions:', resized.metadata);
}

Resizing Images

// Resize to specific dimensions
const result = await processor.resize(imageBuffer, {
  width: 1200,
  height: 800
});

// Resize by width only (maintains aspect ratio)
const widthOnly = await processor.resize(imageBuffer, {
  width: 1000
});

// Resize by height only (maintains aspect ratio)
const heightOnly = await processor.resize(imageBuffer, {
  height: 600
});

// Resize with fit option
const covered = await processor.resize(imageBuffer, {
  width: 800,
  height: 800,
  fit: 'cover' // Options: cover, contain, fill, inside, outside
});

Cropping Images

// Crop to specific dimensions
const cropped = await processor.crop(imageBuffer, {
  width: 1080,
  height: 1080,
  position: 'center' // center, top, bottom, left, right, top-left, etc.
});

// Crop from different positions
const topCrop = await processor.crop(imageBuffer, {
  width: 500,
  height: 500,
  position: 'top'
});

Social Media Aspect Ratios

// Instagram square (1:1 - 1080x1080)
const instagramSquare = await processor.cropForSocialMedia(
  imageBuffer,
  'instagram-square'
);

// Instagram portrait (4:5 - 1080x1350)
const instagramPortrait = await processor.cropForSocialMedia(
  imageBuffer,
  'instagram-portrait'
);

// Instagram story (9:16 - 1080x1920)
const instagramStory = await processor.cropForSocialMedia(
  imageBuffer,
  'instagram-story'
);

// Twitter post (16:9 - 1200x675)
const twitterPost = await processor.cropForSocialMedia(
  imageBuffer,
  'twitter-post'
);

// Facebook cover (2.7:1 - 820x312)
const facebookCover = await processor.cropForSocialMedia(
  imageBuffer,
  'facebook-cover'
);

// YouTube thumbnail (16:9 - 1280x720)
const youtubeThumbnail = await processor.cropForSocialMedia(
  imageBuffer,
  'youtube-thumbnail'
);

Format Conversion

// Convert to WebP
const webp = await processor.toFormat(imageBuffer, {
  format: 'webp',
  quality: 85
});

// Convert to PNG
const png = await processor.toFormat(imageBuffer, {
  format: 'png',
  quality: 90
});

// Convert with metadata stripping
const jpeg = await processor.toFormat(imageBuffer, {
  format: 'jpeg',
  quality: 80,
  stripMetadata: true
});

// Convert to AVIF (modern format with excellent compression)
const avif = await processor.toFormat(imageBuffer, {
  format: 'avif',
  quality: 75
});

Image Optimization

// Optimize with quality reduction
const optimized = await processor.optimize(imageBuffer, {
  quality: 75
});

// Optimize with format conversion
const optimizedWebP = await processor.optimize(imageBuffer, {
  quality: 80,
  format: 'webp'
});

// Optimize and keep metadata
const optimizedWithMetadata = await processor.optimize(imageBuffer, {
  quality: 85,
  stripMetadata: false
});

Thumbnail Generation

// Generate 200x200 square thumbnail
const thumbnail = await processor.thumbnail(imageBuffer, 200);

// Generate smaller thumbnail
const smallThumb = await processor.thumbnail(imageBuffer, 100);

Getting Image Metadata

const metadata = await processor.getMetadata(imageBuffer);

if (metadata.success) {
  console.log('Width:', metadata.metadata?.width);
  console.log('Height:', metadata.metadata?.height);
  console.log('Format:', metadata.metadata?.format);
  console.log('File size:', metadata.metadata?.size, 'bytes');
  console.log('Has alpha:', metadata.metadata?.hasAlpha);
}

Social Media Presets Utilities

import {
  getSocialMediaDimensions,
  isValidPreset,
  SOCIAL_MEDIA_PRESETS
} from '@bernierllc/image-processor';

// Get dimensions for a preset
const dimensions = getSocialMediaDimensions('instagram-square');
console.log(dimensions); // { width: 1080, height: 1080, aspectRatio: '1:1' }

// Check if preset is valid
if (isValidPreset('twitter-post')) {
  const dims = getSocialMediaDimensions('twitter-post');
  console.log('Valid preset:', dims);
}

// Access all presets
console.log(SOCIAL_MEDIA_PRESETS);

Error Handling

All methods return a ProcessResult object with error handling:

const result = await processor.resize(imageBuffer, {
  width: 800,
  height: 600
});

if (result.success) {
  console.log('Success!');
  console.log('Data:', result.data);
  console.log('Metadata:', result.metadata);
} else {
  console.error('Error:', result.error);
}

API Reference

ImageProcessor

Main class for image processing operations.

Methods

resize(input: Buffer, options: ResizeOptions): Promise<ProcessResult>

Resize an image to specified dimensions.

Options:

  • width?: number - Target width in pixels
  • height?: number - Target height in pixels
  • fit?: 'cover' | 'contain' | 'fill' | 'inside' | 'outside' - How to fit image (default: 'inside')
  • withoutEnlargement?: boolean - Prevent enlarging small images (default: false)
crop(input: Buffer, options: CropOptions): Promise<ProcessResult>

Crop an image to specific dimensions.

Options:

  • width: number - Target width in pixels
  • height: number - Target height in pixels
  • position?: CropPosition - Position to crop from (default: 'center')
cropForSocialMedia(input: Buffer, preset: SocialMediaAspectRatio): Promise<ProcessResult>

Crop an image for a social media platform using preset dimensions.

Presets:

  • instagram-square (1:1 - 1080x1080)
  • instagram-portrait (4:5 - 1080x1350)
  • instagram-landscape (1.91:1 - 1080x566)
  • instagram-story (9:16 - 1080x1920)
  • twitter-post (16:9 - 1200x675)
  • twitter-header (3:1 - 1500x500)
  • facebook-post (1.91:1 - 1200x628)
  • facebook-cover (2.7:1 - 820x312)
  • linkedin-post (1.91:1 - 1200x627)
  • youtube-thumbnail (16:9 - 1280x720)
toFormat(input: Buffer, options: FormatOptions): Promise<ProcessResult>

Convert an image to a different format.

Options:

  • format: ImageFormat - Output format ('jpeg', 'png', 'webp', 'avif')
  • quality?: number - Quality setting (1-100, format dependent)
  • stripMetadata?: boolean - Whether to strip metadata (default: false)
optimize(input: Buffer, options: OptimizeOptions): Promise<ProcessResult>

Optimize an image by reducing quality and/or file size.

Options:

  • quality: number - Quality setting (1-100)
  • stripMetadata?: boolean - Whether to strip metadata (default: true)
  • format?: ImageFormat - Target format (default: original format)
thumbnail(input: Buffer, size: number): Promise<ProcessResult>

Generate a square thumbnail from an image.

Parameters:

  • size: number - Thumbnail size in pixels (creates size x size image)
getMetadata(input: Buffer): Promise<ProcessResult>

Get metadata information from an image.

Returns metadata including:

  • width: number - Image width in pixels
  • height: number - Image height in pixels
  • format: string - Image format
  • size: number - File size in bytes
  • space?: string - Color space
  • channels?: number - Number of channels
  • density?: number - Pixel density
  • hasAlpha?: boolean - Whether image has alpha channel

Types

type ImageFormat = 'jpeg' | 'png' | 'webp' | 'avif';

type CropPosition =
  | 'center'
  | 'top'
  | 'bottom'
  | 'left'
  | 'right'
  | 'top-left'
  | 'top-right'
  | 'bottom-left'
  | 'bottom-right';

type SocialMediaAspectRatio =
  | 'instagram-square'
  | 'instagram-portrait'
  | 'instagram-landscape'
  | 'instagram-story'
  | 'twitter-post'
  | 'twitter-header'
  | 'facebook-post'
  | 'facebook-cover'
  | 'linkedin-post'
  | 'youtube-thumbnail';

interface ProcessResult {
  success: boolean;
  data?: Buffer;
  metadata?: ImageMetadata;
  error?: string;
}

interface ImageMetadata {
  width: number;
  height: number;
  format: string;
  size: number;
  space?: string;
  channels?: number;
  density?: number;
  hasAlpha?: boolean;
}

Dependencies

  • @bernierllc/logger - Logging integration
  • sharp - High-performance image processing library

Integration Status

Logger Integration

Status: Integrated

Justification: This package uses @bernierllc/logger for operation logging. Image processing operations (resize, crop, convert) are logged with metadata including dimensions, formats, and processing times. This helps with debugging, performance monitoring, and tracking image processing workflows.

Pattern: Direct integration - logger is a required dependency for this package.

NeverHub Integration

Status: Not applicable

Justification: This is a core utility package that performs image processing operations. It does not participate in service discovery, event publishing, or service mesh operations. Image processing is a stateless utility operation that doesn't require service registration or discovery.

Pattern: Core utility - no service mesh integration needed.

Docs-Suite Integration

Status: Ready

Format: TypeDoc-compatible JSDoc comments are included throughout the source code. All public APIs are documented with examples and type information.

Testing

This package has comprehensive test coverage (90%+) including:

  • Resize operations with various options
  • Crop operations with different positions
  • Social media aspect ratio cropping
  • Format conversions
  • Image optimization
  • Thumbnail generation
  • Metadata extraction
  • Edge cases and error handling
npm test              # Run tests in watch mode
npm run test:run      # Run tests once
npm run test:coverage # Generate coverage report

Examples

Process User Avatars

async function processUserAvatar(uploadBuffer: Buffer) {
  const processor = new ImageProcessor();

  // Generate multiple sizes
  const large = await processor.thumbnail(uploadBuffer, 512);
  const medium = await processor.thumbnail(uploadBuffer, 256);
  const small = await processor.thumbnail(uploadBuffer, 128);

  // Optimize for web
  const optimized = await processor.optimize(uploadBuffer, {
    quality: 85,
    format: 'webp'
  });

  return {
    large: large.data,
    medium: medium.data,
    small: small.data,
    optimized: optimized.data
  };
}

Create Social Media Images

async function createSocialMediaAssets(imageBuffer: Buffer) {
  const processor = new ImageProcessor();

  const assets = {
    instagram: await processor.cropForSocialMedia(imageBuffer, 'instagram-square'),
    twitter: await processor.cropForSocialMedia(imageBuffer, 'twitter-post'),
    facebook: await processor.cropForSocialMedia(imageBuffer, 'facebook-post'),
    youtube: await processor.cropForSocialMedia(imageBuffer, 'youtube-thumbnail')
  };

  // Convert all to WebP for optimal file size
  for (const [platform, result] of Object.entries(assets)) {
    if (result.success && result.data) {
      const webp = await processor.toFormat(result.data, {
        format: 'webp',
        quality: 85
      });
      assets[platform] = webp;
    }
  }

  return assets;
}

Batch Image Optimization

async function optimizeImageDirectory(inputDir: string, outputDir: string) {
  const processor = new ImageProcessor();
  const files = fs.readdirSync(inputDir);

  for (const file of files) {
    if (!file.match(/\.(jpg|jpeg|png)$/i)) continue;

    const inputPath = path.join(inputDir, file);
    const outputPath = path.join(outputDir, file.replace(/\.\w+$/, '.webp'));

    const buffer = fs.readFileSync(inputPath);
    const optimized = await processor.optimize(buffer, {
      quality: 80,
      format: 'webp'
    });

    if (optimized.success) {
      fs.writeFileSync(outputPath, optimized.data!);
      console.log(`Optimized: ${file} -> ${path.basename(outputPath)}`);
    }
  }
}

Performance

The package uses the sharp library, which provides:

  • High-performance image processing
  • Low memory usage
  • Support for large images
  • Hardware acceleration where available

License

Copyright (c) 2025 Bernier LLC. All rights reserved.

See Also