sharp README

The project's README from github.com/lovell/sharp. As one markdown file: README.md.

sharp

sharp logo

The typical use case for this high speed Node-API module is to convert large images in common formats to smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions.

It can be used with all JavaScript runtimes that provide support for Node-API v9, including Node.js (>= 20.9.0), Deno and Bun.

Resizing an image is typically 4x-5x faster than using the quickest ImageMagick and GraphicsMagick settings due to its use of libvips.

Colour spaces, embedded ICC profiles and alpha transparency channels are all handled correctly. Lanczos resampling ensures quality is not sacrificed for speed.

As well as image resizing, operations such as rotation, extraction, compositing and gamma correction are available.

Most modern macOS, Windows and Linux systems do not require any additional install or runtime dependencies.

Documentation

Visit sharp.pixelplumbing.com for complete installation instructions, API documentation, benchmark tests and changelog.

Examples

npm install sharp
// ESM
import sharp from 'sharp';

// CJS
const sharp = require('sharp');
await sharp(inputBuffer)
  .resize({ width: 320, height: 240 })
  .toFile('output.webp', (err, info) => { ... });
const output = await sharp('input.jpg')
  .autoOrient()
  .resize({ width: 200 })
  .jpeg({ mozjpeg: true })
  .toBuffer();
const semiTransparentRedPng = await sharp({
  create: {
    width: 48,
    height: 48,
    channels: 4,
    background: { r: 255, g: 0, b: 0, alpha: 0.5 }
  }
})
  .png()
  .toBuffer();
const roundedCorners = Buffer.from(
  '<svg><rect x="0" y="0" width="200" height="200" rx="50" ry="50"/></svg>'
);

const roundedCornerResizer =
  sharp()
    .resize(200, 200)
    .composite([{
      input: roundedCorners,
      blend: 'dest-in'
    }])
    .png();

readableStream
  .pipe(roundedCornerResizer)
  .pipe(writableStream);

Contributing

A guide for contributors covers reporting bugs, requesting features and submitting code changes.

Licensing

Copyright 2013 Lovell Fuller and others.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

sharp (lovell/sharp)

Searching Database…

32.8K ·GitHub
Что это такое?sharp — это быстрый модуль для обработки изображений в Node.js, работающий на основе библиотеки libvips. Его типичная задача — конвертировать большие изображения в распространённых форматах в файлы поменьше, удобные для веба и разных размеров.
Это библиотека, которую я вызываю из своего кода, или отдельное приложение с интерфейсом?Это библиотека, а не приложение: модуль Node-API, который вы вызываете из собственного кода на JavaScript. Ни графического интерфейса, ни командной строки нет — изменение размеров и конвертация происходят внутри вашей программы.
Как добавить его в проект?Добавьте его как зависимость командой 'npm install sharp'. Полные инструкции по установке и документация по API находятся на sharp.pixelplumbing.com.
Нужно ли мне компилировать libvips или сначала что-то ещё установить?Настраивать libvips вручную не нужно: на большинстве современных macOS, Windows и Linux ничего дополнительно устанавливать не требуется, и зависимостей во время работы тоже нет.
Будет ли это работать на старых версиях Node.js?Нет — нужна среда с поддержкой Node-API v9: Node.js 20.9.0 или новее, либо Deno или Bun. Более старые версии Node.js не поддерживаются.
Насколько это быстро по сравнению с ImageMagick?Изменение размеров обычно выполняется в 4–5 раз быстрее, чем на самых быстрых настройках ImageMagick и GraphicsMagick — благодаря использованию libvips.
Эта скорость не идёт в ущерб качеству изображений?Нет — sharp использует ресемплинг Ланцоша, поэтому скорость не достигается за счёт качества, а цветовые пространства, встроенные ICC-профили и альфа-каналы прозрачности обрабатываются корректно.
Какие форматы изображений он поддерживает?В README названы JPEG, PNG, WebP, GIF и AVIF, в описании репозитория упоминается ещё TIFF, а среди тем на GitHub фигурирует SVG.
Могу ли я использовать sharp в коммерческих проектах?Да — он распространяется по лицензии Apache License 2.0, это разрешительная лицензия, которая допускает коммерческое использование, изменение и распространение.
Creator
lovell
Size
58.8 MB
Stars
32.8K
Age
13y
Commits · 90 Days