Advanced
Get Sharp

Image Processing

This covers the setup and use of the Sharp package for high-performance image processing in Node.js, along with its integration with AWS services like Lambda and S3.

Setting Up Your Project

Step 1: Initialize Node.js Project

Create an empty Node.js package file:

npm init -y

This generates a package.json file that will describe your package dependencies.

Step 2: Install Sharp

Install the Sharp library for high-performance image processing:

npm install sharp

Sharp provides a simple and efficient API to manipulate images in Node.js.

Step 3: Install AWS S3 Client

Install the S3 client sub-package for convenient Amazon S3 interaction:

npm i @aws-sdk/client-s3

This approach allows you to retrieve only what you require instead of installing the entire AWS SDK, keeping your codebase lean and efficient.

Sharp Package Overview

Sharp is a high-performance Node.js image processing library. It's designed to be:

  • Fast: Leverages libvips for rapid image processing
  • Memory-efficient: Minimizes memory allocation
  • Easy to use: Provides a straightforward API

Basic Usage

Here's a simple example of resizing an image with Sharp:

const sharp = require('sharp');
 
sharp('input.jpg')
  .resize(300, 200)
  .toFile('output.jpg')
  .then(info => { console.log(info); })
  .catch(err => { console.error(err); });

AWS Lambda Integration

When using Sharp in an AWS Lambda environment, special considerations are needed due to the differences in the execution environment.

Installation Script for Lambda

The following bash script ensures that Sharp is correctly installed for use in AWS Lambda:

#!/bin/bash
 
cd /workspace/aws-bootcamp-cruddur-2023/aws/lambdas/process-images
 
# Install dependencies
npm install
 
# Remove the sharp directory
rm -rf node_modules/sharp
 
# Install sharp with specific arch, platform, and libc flags
SHARP_IGNORE_GLOBAL_LIBVIPS=1 npm install --arch=x64 --platform=linux --libc=glibc sharp

This script:

  1. Navigates to the project directory
  2. Installs all dependencies
  3. Removes any existing Sharp installation
  4. Reinstalls Sharp with specific flags to ensure compatibility with the Lambda environment

Automating the Installation

You can automate this process by including it in your project's configuration. For example, in a GitPod configuration:

  - name: sharp
    command: |
      source  "$THEIA_WORKSPACE_ROOT/bin/avatar/sharp"

Integrating with AWS S3

const { S3Client, PutObjectCommand } = require("@aws-sdk/client-s3");
const sharp = require('sharp');
const fs = require('fs');
 

The @aws-sdk/client-s3 package allows easy interaction with Amazon S3 from your Node.js application. Refer to Yahya detailed instructions (opens in a new tab) on uploading a processed image to S3 for users profile.

Here is a Sharp re Ship (opens in a new tab).

Get Sharp, Be Sharp.