@neosyn-ee/nest-fastify-media
v0.0.14
Published
High-performance image conversion for NestJS with Fastify
Readme
NestJS Fastify Media Service
A high-performance image processing library for NestJS applications using Fastify. Provides image conversion, resizing, and caching capabilities.
Features
- 🖼️ Multi-format Conversion - Convert between JPEG, PNG, WebP, and more
- 📏 Smart Resizing - Maintain aspect ratio while resizing
- ⚡ In-Memory Caching - Avoid repeated processing of same images
- 🔗 Base64 Output - Get ready-to-use Data URLs
- 🚀 Fastify Optimized - Built for NestJS Fastify adapter
Installation
npm install sharp @nestjs/platform-fastifyQuick Start
- Import Module
import { Module } from '@nestjs/common';
import { NestFastifyMediaService } from 'nest-fastify-media';
@Module({
providers: [NestFastifyMediaService],
exports: [NestFastifyMediaService],
})
export class MediaModule {}- Use in Controller
import { Controller, Get } from '@nestjs/common';
import { NestFastifyMediaService } from 'nest-fastify-media';
@Controller('images')
export class ImageController {
constructor(private readonly mediaService: NestFastifyMediaService) {}
@Get('convert')
async convertImage() {
return {
buffer: await this.mediaService.convertImage({
imageUrl: 'https://example.com/image.jpg',
outputFormat: 'webp',
width: 800,
}),
base64: await this.mediaService.convertImageToBase64({
imageUrl: 'https://example.com/image.jpg',
outputFormat: 'png',
}),
};
}
}API Reference
convertImage(dto: ConvertImageDto): Promise<Buffer>
Converts and resizes an image, returning a Buffer.
convertImageToBase64(dto: ConvertImageDto): Promise<string>
Converts an image and returns as Base64 Data URL.
ConvertImageDto
| Parameter | Type | Default | Description |
| -------------- | -------- | ------- | ----------------------------------- |
| imageUrl | string | - | Source image URL (required) |
| outputFormat | string | png | Output format (jpeg/png/webp) |
| width | number | - | Target width in pixels |
| height | number | - | Target height in pixels |
Examples
Basic Conversion
const buffer = await mediaService.convertImage({
imageUrl: 'https://example.com/photo.jpg',
outputFormat: 'webp',
});Resizing with Base64 Output
const base64 = await mediaService.convertImageToBase64({
imageUrl: 'https://example.com/photo.jpg',
outputFormat: 'png',
width: 300,
height: 200,
});HTML Usage
<img src="data:image/png;base64,..." alt="Converted Image" />Caching
- Automatic in-memory caching
- Cache key format: [url]-[format]-[width]x[height]
- Subsequent identical requests return cached version
