@travetto/image
Version:
Image support, resizing, and optimization
37 lines (27 loc) • 1.54 kB
Markdown
<!-- This file was generated by @travetto/doc and should not be modified directly -->
<!-- Please modify https://github.com/travetto/travetto/tree/main/module/image/DOC.tsx and execute "npx trv doc" to rebuild -->
**Install: @travetto/image**
```bash
npm install @travetto/image
yarn add @travetto/image
```
This module provides functionality for image resizing, and image optimization. This is primarily meant to be used in conjunction with other modules, like the [Email Compilation Support](https://github.com/travetto/travetto/tree/main/module/email-compiler#readme "Email compiling module") module. It can also be invoked directly as needed (as it can be very handy for batch processing images on the command line).
The in process operations leverage [sharp](https://sharp.pixelplumbing.com/) and will perform within expectations, and will execute substantially faster than invoking a subprocess.
**Code: Simple Image Resize**
```typescript
import { createReadStream, createWriteStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';
import { ImageUtil } from '@travetto/image';
export class ResizeService {
async resizeImage(imgPath: string, width: number, height: number): Promise<string> {
const stream = await ImageUtil.convert(createReadStream(imgPath), { w: width, h: height });
const out = imgPath.replace(/[.][^.]+$/, (ext) => `.resized${ext}`);
await pipeline(stream, createWriteStream(out));
return out;
}
}
```