MCPcopy Index your code
hub / github.com/MTSWebServices/image-optimize

github.com/MTSWebServices/image-optimize @v1.6.13

Chat with this repo
repository ↗ · DeepWiki ↗ · release v1.6.13 ↗ · + Follow
39 symbols 85 edges 15 files 5 documented · 13% updated 6d ago★ 74
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Image Optimize

High-performance microservice for on-the-fly image optimization, resizing, and format conversion

Docker Image Docker Pulls Codacy Badge GitHub license Contributor Covenant

Quick StartAPI ReferenceConfigurationDeploymentContributing


Overview

Image Optimize is a lightweight, production-ready microservice that optimizes images dynamically. Built with NestJS and powered by Sharp, it delivers exceptional performance for modern web applications.

Why Image Optimize?

Optimizing images is critical for web performance — reducing page load times, saving bandwidth, and improving SEO rankings. This microservice handles all optimization on-the-fly, requiring no pre-processing or storage of optimized variants.

Features

Feature Description
Dynamic Resizing Resize images to any width, perfect for responsive designs
Smart Compression Reduce file sizes with configurable quality settings (1-100)
Modern Formats Convert to WebP, AVIF, JPEG, or PNG on demand
High Performance Average processing time ~200ms per image
Prometheus Metrics Built-in /metrics endpoint for monitoring
Security Controls Allowlist for sources, size restrictions, Basic Auth support
Docker Ready Production-optimized container image

Quick Start

Using Docker (Recommended)

# Pull and run the latest version
docker run -d --name image-optimize -p 3000:3000 mtsrus/image-optimize

Test the Service

Open in your browser or use curl:

curl "http://localhost:3000/optimize?src=https://example.com/image.png&size=800&format=webp"

Example Request

http://localhost:3000/optimize?src=https://example.com/photo.jpg&size=1200&format=avif&quality=85

API Reference

GET /optimize

Optimizes and returns an image based on the provided parameters.

Parameters

Parameter Type Required Default Description
src string URL-encoded source image URL
size integer Target width in pixels
format string Output format: jpeg, png, webp, avif
quality integer format default Compression quality (1-100)

Response

  • Success (200): Returns the optimized image with appropriate Content-Type header
  • Error (400): Returns JSON with error details

Example

# Convert to WebP with 80% quality, resized to 1920px width
curl -o optimized.webp \
  "http://localhost:3000/optimize?src=https%3A%2F%2Fexample.com%2Fimage.png&size=1920&format=webp&quality=80"

GET /metrics

Returns Prometheus-compatible metrics for monitoring.

curl http://localhost:3000/metrics

Configuration

Configure the service using environment variables:

Core Settings

Variable Default Description
PORT 3000 HTTP server port
SHARP_CONCURRENCY 0 libvips thread count (0 = auto-detect CPU cores)

Security Settings

Variable Default Description
ALLOW_SIZES 100-1920 Allowed output sizes (comma-separated values or ranges)
ALLOW_SOURCES * Allowed source URLs (URL-encoded, comma-separated)
BASIC_AUTHS Basic auth credentials for sources (see format below)

ALLOW_SIZES Examples

# Allow specific sizes only
-e ALLOW_SIZES="320,640,1024,1920"

# Allow a range
-e ALLOW_SIZES="100-2000"

# Mix of specific values and ranges
-e ALLOW_SIZES="320,640,1024-1920"

ALLOW_SOURCES Examples

# Allow images only from specific domains
-e ALLOW_SOURCES="https%3A%2F%2Fcdn.example.com%2F,https%3A%2F%2Fimages.example.org%2F"

BASIC_AUTHS Format

For sources requiring authentication:

# Format: encodeURIComponent(url):encodeURIComponent(login):encodeURIComponent(password)
-e BASIC_AUTHS="https%3A%2F%2Fsecure.example.com%2F:admin:secret123"

Deployment

Docker Compose

services:
  image-optimize:
    image: mtsrus/image-optimize:latest
    restart: always
    ports:
      - "3000:3000"
    environment:
      - PORT=3000
      - ALLOW_SIZES=320,640,1024,1280,1920
      - ALLOW_SOURCES=https%3A%2F%2Fcdn.yoursite.com%2F
    healthcheck:
      test: ["CMD", "wget", "-q", "--spider", "http://localhost:3000/metrics"]
      interval: 30s
      timeout: 10s
      retries: 3

Kubernetes

apiVersion: apps/v1
kind: Deployment
metadata:
  name: image-optimize
spec:
  replicas: 3
  selector:
    matchLabels:
      app: image-optimize
  template:
    metadata:
      labels:
        app: image-optimize
    spec:
      containers:
        - name: image-optimize
          image: mtsrus/image-optimize:latest
          ports:
            - containerPort: 3000
          env:
            - name: ALLOW_SIZES
              value: "320,640,1024,1280,1920"
          resources:
            requests:
              memory: "256Mi"
              cpu: "250m"
            limits:
              memory: "512Mi"
              cpu: "1000m"
          livenessProbe:
            httpGet:
              path: /metrics
              port: 3000
            initialDelaySeconds: 10
            periodSeconds: 30
---
apiVersion: v1
kind: Service
metadata:
  name: image-optimize
spec:
  selector:
    app: image-optimize
  ports:
    - port: 80
      targetPort: 3000

Production Recommendations

  • Scaling: Run multiple replicas behind a load balancer
  • Caching: Use a CDN or reverse proxy (nginx, Varnish) to cache optimized images
  • Memory: Allocate at least 256MB RAM per instance
  • Monitoring: Scrape /metrics endpoint with Prometheus

Frontend Integration

React Component

Use our official React component for seamless integration:

npm install @mts-pjsc/image-optimize
import { Image } from '@mts-pjsc/image-optimize';

<Image
  alt="Optimized image"
  src="https://cdn.example.com/photo.jpg"
/>

The component automatically handles size detection and format negotiation with the optimization service.

👉 image-optimize-react on GitHub


Development

Prerequisites

  • Node.js 24+
  • npm 10+

Local Setup

# Clone the repository
git clone https://github.com/MobileTeleSystems/image-optimize.git
cd image-optimize

# Install dependencies
npm install

# Run in development mode
npm run start:dev

# Run tests
npm test

# Run e2e tests
npm run test:e2e

# Build for production
npm run build

Project Structure

src/
├── controllers/
│   ├── optimize-controller/   # Main optimization endpoint
│   └── metrics/               # Prometheus metrics endpoint
├── services/
│   ├── optimize.service.ts    # Image processing logic (Sharp)
│   ├── img-loader.service.ts  # Remote image fetching
│   └── allow.service.ts       # Security validations
├── enums/
│   └── formats.ts             # Supported output formats
└── main.ts                    # Application entry point

Contributing

We welcome contributions! Please see our Contributing Guide for details.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'feat: add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License — see the LICENSE file for details.


Links


Made with ❤️ by MTS

Core symbols most depended-on inside this repo

getPreview
called by 11
src/controllers/optimize-controller/optimize.controller.ts
writeJson
called by 6
src/services/json-logger.service.ts
bootstrap
called by 1
src/main.ts
getMetrics
called by 1
src/controllers/metrics/metrics.controller.ts
enumFromStringValue
called by 1
src/utils/enumFromStringValue.ts
log
called by 1
src/services/json-logger.service.ts
extraLogs
called by 1
src/services/json-logger.service.ts
getOptimizedImage
called by 1
src/services/optimize.service.ts

Shape

Method 19
Class 16
Enum 2
Function 2

Languages

TypeScript100%

Modules by API surface

src/services/json-logger.service.ts10 symbols
src/services/img-loader.service.ts6 symbols
src/services/allow.service.ts4 symbols
src/controllers/optimize-controller/optimize.controller.ts4 symbols
src/services/optimize.service.ts3 symbols
src/middleware/RequestLoggerMiddleware.ts3 symbols
src/controllers/metrics/metrics.controller.ts3 symbols
src/app.module.ts3 symbols
src/utils/enumFromStringValue.ts1 symbols
src/main.ts1 symbols
src/enums/formats.ts1 symbols

For agents

$ claude mcp add image-optimize \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page