bởi Tobias W.

Sharp is a fast Node-API module for converting and resizing images to web-friendly formats like JPEG, PNG, WebP, GIF, and AVIF. It runs 4–5x faster than ImageMagick, supports streams, and works with Node.js, Deno, and Bun.
This block provides sharp, a high-performance Node-API image processing library built on libvips. It handles resizing, format conversion, compositing, colour manipulation, and metadata operations for JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF, and raw pixel data. The typical buyer is a backend Node.js service that needs fast, production-grade image transformation at scale.
index.js - Entry point; assembles the Sharp constructor by attaching all method modulesindex.d.ts - Full TypeScript type definitions for the entire public APIconstructor.js - Core Sharp class and pipeline state managementinput.js - Input descriptor creation; handles buffers, file paths, streams, and raw dataresize.js - resize(), extend(), extract(), trim() operationscomposite.js - composite() for layering images with blend modesoperation.js - rotate(), flip(), flop(), sharpen(), blur(), gamma(), negate(), and morecolour.js - tint(), greyscale(), toColourspace(), colour pipeline operationschannel.js - removeAlpha(), ensureAlpha(), extractChannel(), joinChannel()output.js - toFile(), toBuffer(), jpeg(), png(), webp(), avif(), gif(), tiff(), raw()utility.js - Static utilities: sharp.cache(), sharp.concurrency(), sharp.versions, sharp.formatis.js - Internal type-checking helpers (not part of public API)libvips.js - libvips version checks and native binding loadersharp.js - Low-level native binding wrapperKhởi chạy sandbox cách ly và chạy phía máy chủ — không cần cài đặt cục bộ.
Tetrees AI Review cho phiên bản này
This Express backend / api completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Quy trình avcp-2026-08-04.1 · SHA-256 f20f3f6160ef6671…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Đã đánh giá 4 thg 8, 2026
Đưa sản phẩm này thẳng vào AI IDE, trình tạo web hoặc cloud IDE của bạn.
Kết nối Tetrees với AI IDE tương thích để liệt kê sản phẩm bạn sở hữu và nhận ZIP đã xác minh mà không cấp quyền tải lên của người bán.
Chưa có đánh giá.
Sign in to join the discussion
Loading discussion…
npm install user@example.com
npm install @img/colour detect-libc semver
sharp ships prebuilt native binaries for most platforms (macOS x64/arm64, Linux x64/arm64, Windows x64). No manual build step is required in most cases. If you are on an unsupported platform or using a custom Node.js ABI, run:
npm install --build-from-source sharp
Ensure Node.js ^18.17.0 or >= 20.3.0 is used. The package requires Node-API v9.
source/ directory into your project, for example at lib/sharp/.lib/sharp/index.js or point your module alias at it:// tsconfig.json
{
"compilerOptions": {
"paths": {
"sharp": ["./lib/sharp/index.d.ts"]
}
}
}
const sharp = require('./lib/sharp/index.js');
import sharp from './lib/sharp/index.js';
// or, if using the published package directly:
import sharp from 'sharp';
sharp.concurrency(n) at startup.declare function sharp(
input?: string | Buffer | ArrayBuffer | Uint8Array | Array<...>,
options?: sharp.SharpOptions
): sharp.Sharp;
Creates a processing pipeline. Pass a file path string, a Buffer, or nothing (for stream input). The returned Sharp instance is a Duplex stream and supports method chaining. Use options.animated: true for multi-frame GIF/WebP processing.
interface Sharp extends Duplex {
resize(width?: number, height?: number, options?: ResizeOptions): Sharp;
rotate(angle?: number, options?: RotateOptions): Sharp;
composite(images: OverlayOptions[]): Sharp;
toFile(fileOut: string, callback?: (err: Error, info: OutputInfo) => void): Promise<OutputInfo>;
toBuffer(options?: ToBufferOptions): Promise<Buffer>;
jpeg(options?: JpegOptions): Sharp;
png(options?: PngOptions): Sharp;
webp(options?: WebpOptions): Sharp;
avif(options?: AvifOptions): Sharp;
gif(options?: GifOptions): Sharp;
tiff(options?: TiffOptions): Sharp;
raw(options?: RawOptions): Sharp;
metadata(): Promise<Metadata>;
stats(): Promise<Stats>;
}
The central chainable instance. Each transformation method returns this, so calls can be composed in any order. Terminal methods (toFile, toBuffer) return Promises when no callback is supplied.
const format: FormatEnum;
A static object describing which input/output formats are available in the current libvips build. Check sharp.format.avif.output.buffer before encoding to AVIF to guard against builds without OpenJPEG or AOM support.
const versions: {
sharp: string;
vips: string;
aom?: string;
heif?: string;
jpeg?: string;
png?: string;
webp?: string;
// ... more
};
Static object exposing the exact versions of sharp and all bundled native libraries. Useful for diagnostics and conditional feature detection at runtime.
Accepts an uploaded buffer, resizes it to a maximum 800px width while preserving aspect ratio, and writes a WebP file optimised for web delivery.
import sharp from './lib/sharp/index.js';
async function processUpload(inputBuffer: Buffer, outputPath: string): Promise<void> {
const info = await sharp(inputBuffer)
.resize({ width: 800, withoutEnlargement: true })
.webp({ quality: 80 })
.toFile(outputPath);
console.log(`Written ${info.format} ${info.width}x${info.height} (${info.size} bytes)`);
}
Loads a base JPEG and overlays a semi-transparent PNG watermark at the bottom-right corner, then returns the result as a buffer for streaming to S3 or a CDN.
import sharp from './lib/sharp/index.js';
import { readFileSync } from 'node:fs';
async function addWatermark(
baseImagePath: string,
watermarkPath: string
): Promise<Buffer> {
const { width = 800, height = 600 } = await sharp(baseImagePath).metadata();
return sharp(baseImagePath)
.composite([
{
input: watermarkPath,
gravity: 'southeast',
blend: 'over',
},
])
.jpeg({ quality: 90, mozjpeg: true })
.toBuffer();
}
Extracts the first frame of an animated GIF, resizes it to a 150x150 cover thumbnail, and saves as PNG. Uses pages: 1 to avoid processing all frames.
import sharp from './lib/sharp/index.js';
async function gifThumbnail(inputPath: string, outputPath: string): Promise<void> {
await sharp(inputPath, { pages: 1 })
.resize(150, 150, { fit: 'cover', position: 'entropy' })
.png({ compressionLevel: 9 })
.toFile(outputPath);
}
Attach sharp as a transform stream between a read stream and a write stream for memory-efficient large file processing.
import sharp from './lib/sharp/index.js';
import { createReadStream, createWriteStream } from 'node:fs';
function streamResize(inputFile: string, outputFile: string): void {
const transformer = sharp()
.resize(1280, 720, { fit: 'inside' })
.avif({ quality: 60 });
createReadStream(inputFile)
.pipe(transformer)
.pipe(createWriteStream(outputFile));
}
index.js - Requires constructor.js then mutates the class prototype by passing it through each feature module; this is the only file you should import.index.d.ts - Canonical TypeScript declarations; contains all interfaces (SharpOptions, ResizeOptions, OutputInfo, etc.) and the sharp function overloads.constructor.js - Instantiates the Sharp Duplex stream, initialises this.options, and stores pipeline state.input.js - Parses and validates input descriptors (file path, buffer, stream, create, text, raw); attaches metadata() and stats().resize.js - Implements resize(), extend(), extract(), and trim() with full option validation.composite.js - Implements composite(), accepting an array of overlay descriptors with blend mode, gravity, and offset options.operation.js - Geometric and tonal operations: rotate(), autoOrient(), flip(), flop(), sharpen(), median(), blur(), flatten(), unflatten(), gamma(), negate(), normalise(), clahe(), convolve(), threshold(), boolean(), linear(), recomb(), modulate().colour.js - tint(), greyscale() / grayscale(), pipelineColourspace(), toColourspace() / toColorspace().channel.js - Alpha and channel operations: removeAlpha(), ensureAlpha(), extractChannel(), joinChannel(), bandBoolOp().output.js - All output format encoders and terminal methods; maps file extensions to libvips format names.utility.js - Static methods on the constructor: cache(), concurrency(), counters(), simd(), queue.is.js - Internal predicates (defined, integer, inRange, etc.); not exported publicly.libvips.js - Loads the prebuilt native .node binding and validates the libvips version at require time.sharp.js - Thin wrapper that exposes the raw Node-API binding object consumed by the JS layer.npm ci on a different OS/arch: Run npm rebuild sharp or delete node_modules/sharp and reinstall on the target platform.Error: Input file is missing on relative paths: sharp resolves paths relative to process.cwd(), not __dirname; use path.resolve(__dirname, 'file.jpg').{ animated: true } in SharpOptions; default reads only the first frame.JP2 output requires libvips with support for OpenJPEG: The prebuilt binary for your platform omits OpenJPEG; build from source with npm install --build-from-source sharp.sharp buffers are backed by libvips memory; call sharp.cache(false) in long-running services if RSS grows unbounded, and tune sharp.concurrency(n) to match available CPU cores.import sharp from 'sharp' fails with ERR_REQUIRE_ESM or default export undefined: sharp is CJS; use import sharp from 'sharp' with "esModuleInterop": true in tsconfig, or use createRequire in pure ESM contexts.I have the sharp image processing library source copied into `lib/sharp/` in my project.
I also have `USAGE.md` in the same directory describing its API and integration steps.
The upstream npm package is `user@example.com`.
Please help me integrate sharp into my project step by step:
1. Read `USAGE.md` and `lib/sharp/index.d.ts` to understand the available API.
2. Install all required runtime dependencies listed in `USAGE.md`.
3. Create a TypeScript module at `src/images/processor.ts` that exports:
- `resizeImage(input: Buffer, width: number, height: number): Promise<Buffer>`
- `convertToWebP(inputPath: string, outputPath: string, quality?: number): Promise<void>`
- `addWatermark(basePath: string, watermarkPath: string): Promise<Buffer>`
4. Wire the module into my Express route at `src/routes/upload.ts`.
5. Only use methods and types that are present in `lib/sharp/index.d.ts` and documented in `USAGE.md`.
6. Do not install the published `sharp` npm package; import from `lib/sharp/index.js` instead.
7. Show the final contents of each modified file.
The JavaScript source and TypeScript definitions in source/ are dual-licensed:
.js implementation files) - Copyright 2013 Lovell Fuller and others.index.d.ts type definitions) - Copyright 2017 François Nguyen and others.Upstream repository and full documentation: https://sharp.pixelplumbing.com
npm: sharp on npmjs.com
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
Hướng dẫn cài đặt đầy đủ và prompt tích hợp sẽ mở khóa sau khi mua.
Automation, Utilities & Developer Tools
Miễn phí