Working with Images in TypeScript: resize and crop
In modern web development, image processing is one of the most in-demand tasks. TypeScript, thanks to its strict typing and integration with Node.js, allows you to create reliable and performant tools for resizing and cropping images. In this article, we will look at two popular libraries: Sharp (server-side processing) and Jimp (pure JavaScript), as well as a native approach using the Canvas API for the browser.
1. Setting up a TypeScript project
To start, create a project and install the necessary dependencies:
npm init -ynpm install typescript @types/node sharp jimpnpx tsc --initIn the tsconfig.json file, make sure "module": "commonjs" and "target": "ES2020" are set.
2. Sharp library — fast server-side processing
Sharp uses the native libvips module and provides high performance. It is suitable for server-side applications (NestJS, Express).
2.1. Resizing with Sharp
The resize() method takes width and height. You can specify only one parameter — the second will be calculated proportionally.
import sharp from 'sharp';
async function resizeImage(inputPath: string, outputPath: string, width: number, height?: number): Promise<void> { try { await sharp(inputPath) .resize(width, height, { fit: 'cover', // 'cover', 'contain', 'fill', 'inside', 'outside' position: 'center' // position for cropping when using cover }) .toFile(outputPath); console.log(`Image resized: ${outputPath}`); } catch (error) { console.error('Resize error:', error); }}
// Usage exampleresizeImage('input.jpg', 'output_800x600.jpg', 800, 600);2.2. Cropping with Sharp
The extract() method allows you to cut out a rectangular area. Parameters: left, top, width, height.
async function cropImage( inputPath: string, outputPath: string, left: number, top: number, cropWidth: number, cropHeight: number): Promise<void> { try { await sharp(inputPath) .extract({ left, top, width: cropWidth, height: cropHeight }) .toFile(outputPath); console.log(`Cropping completed: ${outputPath}`); } catch (error) { console.error('Crop error:', error); }}
// Example: cut out a 400x400 center from an 800x600 imagecropImage('input.jpg', 'cropped_center.jpg', 200, 100, 400, 400);2.3. Combining resize and crop
Sharp allows you to chain operations. For example, first resize, then crop:
async function resizeAndCrop(inputPath: string, outputPath: string): Promise<void> { await sharp(inputPath) .resize(500, 500, { fit: 'inside' }) // resize to 500x500 without cropping .extract({ left: 50, top: 50, width: 400, height: 400 }) // crop the center .toFile(outputPath);}
resizeAndCrop('input.jpg', 'processed.jpg');3. Jimp library — pure JavaScript without native dependencies
Jimp works on pure JavaScript and does not require installing additional system libraries. It is ideal for isolated environments (e.g., AWS Lambda).
3.1. Installing Jimp
npm install jimpnpm install @types/jimp // for TypeScript3.2. Resizing with Jimp
import Jimp from 'jimp';
async function resizeWithJimp(inputPath: string, outputPath: string, width: number, height: number): Promise<void> { try { const image = await Jimp.read(inputPath); image.resize(width, height, Jimp.RESIZE_BILINEAR); // algorithms: BILINEAR, BICUBIC, NEAREST_NEIGHBOR awa Also in library
Internationalization (i18n) in Rust: gettext-rs and fluent-rs libraries
JMH Java Guide: Complete Microbenchmarking Tutorial
range-v3 for C++: Complete Guide with Examples
SignalR for C# (.NET): Complete Guide with Examples
OAuth client for TypeScript: authorization via GitHub, Google and other providers