CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-sharp

High performance Node.js image processing library for resizing JPEG, PNG, WebP, GIF, AVIF and TIFF images

80

1.01x
Overview
Eval results
Files

color-channels.mddocs/

Color and Channels

Sharp provides comprehensive color space management and channel manipulation capabilities for professional image processing workflows.

Capabilities

Color Space Management

Convert between different color spaces and manage pipeline color processing.

/**
 * Set pipeline color space for internal processing
 * @param colourspace - Pipeline color space identifier
 * @returns Sharp instance for chaining
 */
pipelineColourspace(colourspace?: string): Sharp;

/**
 * Alternative spelling of pipelineColourspace
 * @param colorspace - Pipeline color space identifier
 * @returns Sharp instance for chaining
 */
pipelineColorspace(colorspace?: string): Sharp;

/**
 * Set output color space
 * @param colourspace - Output color space identifier
 * @returns Sharp instance for chaining
 */
toColourspace(colourspace?: string): Sharp;

/**
 * Alternative spelling of toColourspace
 * @param colorspace - Output color space identifier
 * @returns Sharp instance for chaining
 */
toColorspace(colorspace?: string): Sharp;

Supported Color Spaces:

  • srgb - Standard RGB (default output)
  • rgb - Linear RGB
  • rgb16 - 16-bit RGB
  • scrgb - scRGB color space
  • cmyk - CMYK for print
  • lab - LAB color space
  • lch - LCH color space
  • hsv - HSV color space
  • xyz - XYZ color space
  • b-w - Black and white (single channel)
  • grey16 - 16-bit greyscale
  • multiband - Multiple bands

Usage Examples:

// Set pipeline to work in LAB color space
await sharp('input.jpg')
  .pipelineColourspace('lab')
  .modulate({ lightness: 10 })
  .toColourspace('srgb')
  .toFile('lab-processed.jpg');

// Convert to CMYK for print
await sharp('input.jpg')
  .toColorspace('cmyk')
  .tiff()
  .toFile('print-ready.tiff');

// High bit depth processing
await sharp('input.tiff')
  .pipelineColorspace('rgb16')
  .gamma(2.2)
  .toColorspace('srgb')
  .toFile('processed-16bit.jpg');

Color Tinting

Apply color tints to images.

/**
 * Tint image using specified color
 * @param tint - Color for tinting (string or RGBA object)
 * @returns Sharp instance for chaining
 */
tint(tint: string | RGBA): Sharp;

interface RGBA {
  r?: number;
  g?: number;
  b?: number;
  alpha?: number;
}

Usage Examples:

// Sepia tint using color string
await sharp('input.jpg')
  .tint('#704214')
  .toFile('sepia.jpg');

// Blue tint using RGBA object
await sharp('input.jpg')
  .tint({ r: 100, g: 150, b: 255 })
  .toFile('blue-tinted.jpg');

// Subtle warm tint
await sharp('input.jpg')
  .tint('rgb(255, 240, 220)')
  .toFile('warm-tinted.jpg');

Greyscale Conversion

Convert images to greyscale with proper gamma handling.

/**
 * Convert to 8-bit greyscale
 * @param greyscale - Enable greyscale conversion (defaults to true)
 * @returns Sharp instance for chaining
 */
greyscale(greyscale?: boolean): Sharp;

/**
 * Alternative spelling of greyscale
 * @param grayscale - Enable greyscale conversion (defaults to true)
 * @returns Sharp instance for chaining
 */
grayscale(grayscale?: boolean): Sharp;

Usage Examples:

// Basic greyscale conversion
await sharp('input.jpg')
  .greyscale()
  .toFile('greyscale.jpg');

// Greyscale with gamma correction for better results
await sharp('input.jpg')
  .gamma(2.2)
  .greyscale()
  .gamma(1/2.2)
  .toFile('gamma-corrected-grey.jpg');

// Conditional greyscale
const shouldConvert = true;
await sharp('input.jpg')
  .grayscale(shouldConvert)
  .toFile('output.jpg');

Alpha Channel Management

Control transparency channels in images.

/**
 * Remove alpha channel if present
 * @returns Sharp instance for chaining
 */
removeAlpha(): Sharp;

/**
 * Ensure alpha channel exists
 * @param alpha - Transparency level (0-1, defaults to 1)
 * @returns Sharp instance for chaining
 */
ensureAlpha(alpha?: number): Sharp;

/**
 * Merge alpha channel with background
 * @param flatten - Enable flattening or options
 * @returns Sharp instance for chaining
 */
flatten(flatten?: boolean | FlattenOptions): Sharp;

/**
 * Make white pixels fully transparent
 * @returns Sharp instance for chaining
 */
unflatten(): Sharp;

interface FlattenOptions {
  /** Background color for flattening */
  background?: string | RGBA;
}

Usage Examples:

// Remove alpha channel
await sharp('input.png')
  .removeAlpha()
  .jpeg()
  .toFile('no-alpha.jpg');

// Add alpha channel
await sharp('input.jpg')
  .ensureAlpha(0.8)
  .png()
  .toFile('semi-transparent.png');

// Flatten with custom background
await sharp('input.png')
  .flatten({ background: '#ffffff' })
  .jpeg()
  .toFile('flattened-white.jpg');

// Make white areas transparent
await sharp('input.jpg')
  .unflatten()
  .png()
  .toFile('white-transparent.png');

Channel Extraction and Manipulation

Extract and manipulate individual color channels.

/**
 * Extract single channel from multi-channel image
 * @param channel - Channel to extract (0-3 or color name)
 * @returns Sharp instance for chaining
 */
extractChannel(channel: 0 | 1 | 2 | 3 | 'red' | 'green' | 'blue' | 'alpha'): Sharp;

/**
 * Join additional channels to image
 * @param images - Channel images to join
 * @param options - Options for channel images
 * @returns Sharp instance for chaining
 */
joinChannel(images: string | Buffer | (string | Buffer)[], options?: SharpOptions): Sharp;

/**
 * Perform bitwise boolean operation on all channels
 * @param boolOp - Boolean operation type
 * @returns Sharp instance for chaining
 */
bandbool(boolOp: 'and' | 'or' | 'eor'): Sharp;

Usage Examples:

// Extract red channel
await sharp('input.jpg')
  .extractChannel('red')
  .toFile('red-channel.jpg');

// Extract alpha channel
await sharp('input.png')
  .extractChannel(3)
  .toFile('alpha-mask.png');

// Join additional channels
const baseImage = sharp('rgb-input.jpg');
const alphaChannel = sharp('alpha-mask.png');

await baseImage
  .joinChannel(alphaChannel.toBuffer(), { raw: { width: 800, height: 600, channels: 1 } })
  .png()
  .toFile('rgba-output.png');

// Boolean operation across channels
await sharp('input.png')
  .bandbool('and')
  .toFile('channels-and.png');

Advanced Channel Operations

Perform bitwise operations between images.

/**
 * Perform bitwise boolean operation with operand image
 * @param operand - Operand image (Buffer or file path)
 * @param operator - Boolean operation type
 * @param options - Options for raw pixel data
 * @returns Sharp instance for chaining
 */
boolean(operand: string | Buffer, operator: 'and' | 'or' | 'eor', options?: BooleanOptions): Sharp;

interface BooleanOptions {
  /** Raw pixel data description */
  raw?: Raw;
}

interface Raw {
  width: number;
  height: number;
  channels: 1 | 2 | 3 | 4;
}

Usage Examples:

// AND operation with mask
await sharp('input.png')
  .boolean('mask.png', 'and')
  .toFile('masked.png');

// XOR operation for difference detection
await sharp('image1.png')
  .boolean('image2.png', 'eor')
  .toFile('differences.png');

// OR operation for combining masks
await sharp('mask1.png')
  .boolean('mask2.png', 'or')
  .toFile('combined-mask.png');

Color Constants and Utilities

Sharp provides constants for color-related operations.

// Available via sharp.bool
interface BoolEnum {
  and: 'and';
  or: 'or';
  eor: 'eor';
}

// Available color spaces
interface ColourspaceEnum {
  'b-w': string;
  'cmc': string;
  'cmyk': string;
  'fourier': string;
  'grey16': string;
  'histogram': string;
  'hsv': string;
  'lab': string;
  'labq': string;
  'labs': string;
  'lch': string;
  'matrix': string;
  'multiband': string;
  'rgb': string;
  'rgb16': string;
  'scrgb': string;
  'srgb': string;
  'xyz': string;
  'yxy': string;
}

Usage Example:

// Using boolean constants
await sharp('input.png')
  .boolean('mask.png', sharp.bool.and)
  .toFile('result.png');

Color Processing Patterns

Color Grading Workflow:

const colorGrade = async (input, output) => {
  await sharp(input)
    .pipelineColourspace('lab')
    .modulate({
      brightness: 1.05,
      saturation: 1.1
    })
    .linear([1.02, 0.98, 1.01], [5, -2, 8])
    .toColourspace('srgb')
    .toFile(output);
};

Channel Mixing for B&W:

const customBW = async (input, output) => {
  await sharp(input)
    .recomb([
      [0.299, 0.587, 0.114],  // Luminance weights
      [0.299, 0.587, 0.114],
      [0.299, 0.587, 0.114]
    ])
    .toFile(output);
};

Alpha Compositing:

const alphaComposite = async (base, overlay, output) => {
  const baseImage = sharp(base);
  const overlayWithAlpha = await sharp(overlay)
    .ensureAlpha(0.7)
    .toBuffer();
    
  await baseImage
    .composite([{
      input: overlayWithAlpha,
      blend: 'over'
    }])
    .toFile(output);
};

Type Definitions

type Colour = string | RGBA;
type Color = Colour; // Alternative spelling

interface RGBA {
  r?: number;
  g?: number;
  b?: number;
  alpha?: number;
}

type Channels = 1 | 2 | 3 | 4;

Install with Tessl CLI

npx tessl i tessl/npm-sharp

docs

color-channels.md

composition.md

constructor-input.md

index.md

metadata-stats.md

operations-filters.md

output-formats.md

resize-geometry.md

utilities-performance.md

tile.json