home / skills / aidotnet / moyucode / sharp

sharp skill

/skills/tools/sharp

This skill optimizes image processing tasks by resizing, converting formats, and applying enhancements with a high-performance Node.js library.

npx playbooks add skill aidotnet/moyucode --skill sharp

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
3.1 KB
---
name: sharp
description: 高性能Node.js图片处理库。使用libvips最快速地调整JPEG、PNG、WebP、AVIF和TIFF图片大小。
metadata:
  short-description: 高性能图片处理
source:
  repository: https://github.com/lovell/sharp
  license: Apache-2.0
  stars: 29k+
---

# Sharp Tool

## Description
High-performance image processing for resizing, converting, and manipulating images.

## Source
- Repository: [lovell/sharp](https://github.com/lovell/sharp)
- License: Apache-2.0

## Installation

```bash
npm install sharp
```

## Usage Examples

### Resize Image

```typescript
import sharp from 'sharp';

// Resize to specific dimensions
await sharp('input.jpg')
  .resize(800, 600)
  .toFile('output.jpg');

// Resize with aspect ratio preserved
await sharp('input.jpg')
  .resize(800, null)  // Width 800, auto height
  .toFile('output.jpg');

// Resize with fit options
await sharp('input.jpg')
  .resize(800, 600, {
    fit: 'cover',      // cover, contain, fill, inside, outside
    position: 'center' // center, top, right, bottom, left
  })
  .toFile('output.jpg');
```

### Convert Format

```typescript
// Convert to WebP
await sharp('input.jpg')
  .webp({ quality: 80 })
  .toFile('output.webp');

// Convert to AVIF (modern format)
await sharp('input.jpg')
  .avif({ quality: 60 })
  .toFile('output.avif');

// Convert to PNG with transparency
await sharp('input.jpg')
  .png({ compressionLevel: 9 })
  .toFile('output.png');
```

### Image Manipulation

```typescript
// Rotate and flip
await sharp('input.jpg')
  .rotate(90)
  .flip()
  .toFile('output.jpg');

// Blur and sharpen
await sharp('input.jpg')
  .blur(5)
  .sharpen()
  .toFile('output.jpg');

// Grayscale and tint
await sharp('input.jpg')
  .grayscale()
  .tint({ r: 255, g: 128, b: 0 })
  .toFile('output.jpg');

// Crop
await sharp('input.jpg')
  .extract({ left: 100, top: 100, width: 500, height: 300 })
  .toFile('output.jpg');
```

### Add Watermark

```typescript
async function addWatermark(input: string, watermark: string, output: string) {
  const image = sharp(input);
  const { width, height } = await image.metadata();
  
  // Resize watermark
  const watermarkBuffer = await sharp(watermark)
    .resize(Math.round(width! * 0.2))
    .toBuffer();
  
  await image
    .composite([{
      input: watermarkBuffer,
      gravity: 'southeast',
      blend: 'over',
    }])
    .toFile(output);
}
```

### Generate Thumbnails

```typescript
async function generateThumbnails(input: string, sizes: number[]) {
  const image = sharp(input);
  
  await Promise.all(sizes.map(size =>
    image
      .clone()
      .resize(size, size, { fit: 'cover' })
      .jpeg({ quality: 80 })
      .toFile(`thumb-${size}.jpg`)
  ));
}

// Usage
await generateThumbnails('photo.jpg', [64, 128, 256, 512]);
```

### Stream Processing

```typescript
import { createReadStream, createWriteStream } from 'fs';

// Process large images with streams
createReadStream('large-input.jpg')
  .pipe(sharp().resize(1920, 1080).jpeg({ quality: 85 }))
  .pipe(createWriteStream('output.jpg'));
```

## Tags
`image`, `resize`, `convert`, `thumbnail`, `processing`

## Compatibility
- Codex: ✅
- Claude Code: ✅

Overview

This skill provides a high-performance Node.js image-processing tool powered by libvips for fast resizing, format conversion, and pixel manipulation. It supports JPEG, PNG, WebP, AVIF and TIFF with memory-efficient streaming and asynchronous APIs. Use it to build image pipelines for web, mobile, and server-side workflows that need speed and low resource usage.

How this skill works

The library reads images from files, buffers, or streams, applies a chain of transformations (resize, crop, rotate, blur, color adjustments, composite), and writes output in the requested format. It leverages libvips for multi-threaded, low-memory operations and exposes convenient methods for cloning pipelines, streaming large files, and producing buffers or files. You can compose operations synchronously in code and run many tasks in parallel via Promise.all or streaming pipelines.

When to use it

  • Generate responsive images and thumbnails for websites or CDNs
  • Convert images to modern formats (WebP, AVIF) to reduce bandwidth
  • Process large images efficiently using streams to avoid memory spikes
  • Add watermarks or overlays during image publishing workflows
  • Create on-the-fly image transformations in serverless or microservice environments

Best practices

  • Prefer streams for very large images to reduce memory usage
  • Clone pipeline instances before producing multiple variants to avoid side effects (use .clone())
  • Set explicit output quality/compression options for predictable file sizes
  • Resize before complex filters or composites to speed processing
  • Use Promise.all with care to limit concurrency and avoid overwhelming CPU/memory

Example use cases

  • Batch-generate thumbnails in several sizes for a gallery and save as optimized JPEGs
  • Convert uploaded user images to WebP/AVIF with fallbacks for browsers that lack support
  • Implement server-side image resizing endpoint that accepts width/height and returns streamed output
  • Add branded watermark to photos during publication by compositing a resized watermark in the corner
  • Build a background job that sharpens, color-corrects, and archives TIFF scans as compressed PNGs

FAQ

Can I process images from HTTP streams?

Yes. The API accepts streams; pipe an incoming request through the processing pipeline and then to a writable stream or response.

How do I avoid excessive memory usage when resizing many images?

Use streaming, limit concurrent jobs with a task queue, and resize early in the pipeline. Avoid creating large in-memory buffers for each job.