JavaScript Image Processing with Sharp

Photo by Jess Bailey on Unsplash

JavaScript Image Processing with Sharp

joshxyzhimself's photo
·Jul 25, 2022·

2 min read


Sharp is a JavaScript module for image processing.

Use Cases

  • Converting an image from one format to another
  • Resizing a large image into a smaller web-friendly image
  • Compositing / combining layers of images
  • Image operations such as rotate, flip, sharpen, blur, and so on
  • Color manipulation, channel manipulation

More info here: Docs

Supported Environments

  • Node.js

Why Sharp

  • It's fast, up to 4x - 5x faster than ImageMagick and GraphisMagick due to its use of libvips.
  • It's flexible, it supports inputs of JPEG, PNG, WebP, GIF, AVIF, TIFF and SVG; and outputs of JPEG, PNG, WebP, GIF, AVIF and TIFF formats as well as uncompressed raw pixel data; you may also use streams and buffers.
  • It's optimal, has built-in features of mozjpeg and pngquant for efficient optimization of JPEG and PNG files.

More info here: Docs


npm install sharp


// CommonJS
const fs = require('fs');
const path = require('path');
const sharp = require('sharp');

// ECMAScript
import fs from 'fs';
import path from 'path';
import { default as sharp } from 'sharp';

process.nextTick(async () => {

  // process.cwd() here is our current working directory
  const process_cwd_path = process.cwd();

  // define the source file path
  const file_path =  path.join(process_cwd_path, 'image.png');

  // read image data from source file path
  const file_buffer = await fs.promises.readFile(file_path);

  // convert image data into mozjpeg format
  const converted_buffer = await sharp(file_buffer).jpeg({ mozjpeg: true }).toBuffer();

  // define the destination file path
  const converted_file_path =  path.join(process_cwd_path, 'converted.jpg');

  // write converted data into destination file path
  await fs.promises.writeFile(converted_file_path, converted_buffer);