Skip to content

cp949/web-image-util

Repository files navigation

@cp949/web-image-util

🎨 High-performance TypeScript library for image processing in modern web browsers

A browser-native image processing library built on Canvas 2D API with intuitive chaining API pattern for web browser environments.

npm version License: MIT TypeScript

✨ Key Features

  • πŸ”— Chainable API: Intuitive method chaining pattern
  • 🎯 Complete Type Safety: Full TypeScript support with discriminated union types
  • 🌐 Browser Native: Canvas API-based, zero external dependencies
  • πŸ“¦ Tree-shakable: ES modules for optimal bundle size
  • ⚑ High Performance: Canvas pooling and memory optimization
  • 🎨 Modern Formats: WebP, JPEG, PNG support (AVIF with browser support)
  • πŸ“± Responsive Ready: Optimized for various screen sizes and devices
  • πŸ–ΌοΈ Advanced SVG: High-quality SVG processing with vector preservation

πŸš€ Quick Start

npm install @cp949/web-image-util
import { processImage } from '@cp949/web-image-util';

// πŸ†• Recommended: New ResizeConfig API
const thumbnail = await processImage(source)
  .resize({ fit: 'cover', width: 300, height: 200 })
  .toBlob();

// Advanced image processing
const result = await processImage(source)
  .resize({ fit: 'cover', width: 800, height: 600, background: '#ffffff' })
  .blur(2)
  .toBlob({ format: 'webp', quality: 0.8 });

// Social media image
const instagramPost = await processImage(source)
  .resize({ fit: 'cover', width: 1080, height: 1080 })
  .toFile('instagram-post.jpg');

πŸ“š Library Architecture

This is a monorepo built with Turbo and pnpm workspaces, containing:

  • Core Library (sub/web-image-util/) - The main image processing package
  • Demo App (apps/exam/) - Interactive Next.js application showcasing all features
  • Shared Configs - ESLint and TypeScript configurations

πŸ“¦ Core Library Features

The main library provides comprehensive image processing capabilities:

🎯 Advanced Resize Engine

// Precise size control with 5 fit modes
processImage(source).resize({ fit: 'cover', width: 300, height: 200 })   // Crop to fit (maintain ratio, fill area)
processImage(source).resize({ fit: 'contain', width: 300, height: 200 }) // Fit within bounds (show full image)
processImage(source).resize({ fit: 'fill', width: 300, height: 200 })    // Stretch to exact size (ignore ratio)

// Smart size constraints (shrink only, no enlargement)
processImage(source).resize({ fit: 'maxFit', width: 800, height: 600 })  // Max 800x600 bounds
processImage(source).resize({ fit: 'maxFit', width: 800 })               // Max width 800px
processImage(source).resize({ fit: 'maxFit', height: 600 })              // Max height 600px

// Size guarantee (enlarge only, no shrinking)
processImage(source).resize({ fit: 'minFit', width: 400, height: 300 })  // Min 400x300 guarantee
processImage(source).resize({ fit: 'minFit', width: 300 })               // Min width 300px guarantee

🎨 Image Effects & Filters

// Basic blur effect
const blurred = await processImage(source)
  .resize({ fit: 'cover', width: 400, height: 300 })
  .blur(2)  // Blur radius 2px
  .toBlob();

// Advanced features (advanced subpackage) - Watermarks
import { SimpleWatermark } from '@cp949/web-image-util/advanced';

// Text watermark
const canvas = await processImage(source).resize({ fit: 'cover', width: 400, height: 300 }).toCanvas();
const watermarked = SimpleWatermark.addText(canvas, {
  text: 'Β© 2024 Company Name',
  position: 'bottom-right',
  style: 'white-shadow'
});

πŸ“€ Output Formats & Optimization

// Multiple output types (extended)
const blob = await processImage(source).toBlob({ format: 'webp', quality: 0.8 });
const dataURL = await processImage(source).toDataURL({ format: 'jpeg', quality: 0.9 });
const file = await processImage(source).toFile('image.png');
const canvas = await processImage(source).toCanvas();
const element = await processImage(source).toElement();     // HTMLImageElement
const arrayBuffer = await processImage(source).toArrayBuffer(); // ArrayBuffer
const uint8Array = await processImage(source).toUint8Array();   // Uint8Array

// Format-optimized settings
const webpResult = await processImage(source)
  .resize({ fit: 'cover', width: 800, height: 600 })
  .toBlob({ format: 'webp', quality: 0.8 });  // WebP for high compression

const jpegResult = await processImage(source)
  .resize({ fit: 'cover', width: 800, height: 600 })
  .toBlob({ format: 'jpeg', quality: 0.85 }); // JPEG for photos

πŸŽ›οΈ Convenience Functions (Presets)

import { createThumbnail, createAvatar, createSocialImage } from '@cp949/web-image-util/presets';

// Quick thumbnail generation
const thumbnail = await createThumbnail(source, {
  size: 150,
  format: 'webp',
  quality: 0.8
});

// Avatar image (square + rounded)
const avatar = await createAvatar(source, {
  size: 120,
  background: '#f0f0f0'
});

// Social media formats
const igPost = await createSocialImage(source, { platform: 'instagram' });
const fbCover = await createSocialImage(source, { platform: 'facebook' });

⚑ Batch Processing

// Parallel processing (using Promise.all)
const sources = [image1, image2, image3];

const results = await Promise.all(
  sources.map(source =>
    processImage(source)
      .resize({ fit: 'cover', width: 300, height: 200 })
      .toBlob({ format: 'webp', quality: 0.8 })
  )
);

// Sequential processing (memory efficient)
const batchResults = [];
for (const source of sources) {
  const result = await processImage(source)
    .resize({ fit: 'cover', width: 400, height: 300 })
    .toBlob();
  batchResults.push(result);
}

πŸ› οΈ Utilities & Conversion

import {
  convertToBlob,
  convertToDataURL,
  convertToFile,
  convertToElement,
  enhanceBrowserCompatibility,
  features
} from '@cp949/web-image-util';

// SVG compatibility enhancement
const { enhanced, report } = enhanceBrowserCompatibility(svgString, {
  fixDimensions: true,
  addNamespaces: true
});

// Convert image source to HTMLImageElement
const imageElement = await convertToElement(blob);

// Direct conversion (without chaining)
const blob = await convertToBlob(canvas, { format: 'webp', quality: 0.8 });

// Browser feature support detection
console.log('WebP support:', features.webp);
console.log('AVIF support:', features.avif);
console.log('OffscreenCanvas support:', features.offscreenCanvas);

πŸ–₯️ Interactive Demo Application

πŸ“± Live Demo & Testing Platform

A comprehensive Next.js 15 application built with React 19 and Material-UI, showcasing all library features in a real web environment.

🌐 Live Demo: Start here (after running pnpm dev)

🎨 Feature Demo Pages

  1. 🏠 Homepage

    • Library overview and key features
    • Quick start guide
    • Live code examples
  2. πŸ“ Basic Processing

    • Resize fit mode comparison (cover, contain, fill, maxFit, minFit)
    • Real-time preview with Before/After comparison
    • Interactive size adjustment sliders
  3. 🎨 Advanced Features

    • Watermark addition (text/image)
    • Image composition and layer management
    • Blur effects and basic filters
  4. πŸ“± Presets

    • Social media format auto-conversion
    • Thumbnail generator
    • Avatar creator
  5. πŸ”„ Converters

    • Format conversion (JPEG ↔ PNG ↔ WebP)
    • Quality adjustment and compression comparison
    • File size optimization
  6. πŸ“¦ Batch Processing

    • Multi-file upload
    • Bulk conversion and ZIP download
    • Progress indicators and performance stats
  7. ⚑ Performance Testing

    • Processing time benchmarks
    • Memory usage analysis
    • Large image processing tests
  8. πŸ› οΈ Developer Tools

    • Image metadata display
    • Debug information and logs
    • API call monitoring
  9. 🎯 Filter System

    • Plugin-based filter architecture
    • Custom filter creation
    • Filter chains and presets
  10. πŸ–ΌοΈ SVG Compatibility

    • SVG rasterization
    • Compatibility enhancement options
    • Cross-browser rendering comparison

πŸŽ›οΈ Interactive UI Features

  • Drag & Drop File Upload: Intuitive file selection with visual feedback
  • Real-time Parameter Sliders: Instant preview of processing changes
  • Before/After Comparison View: Side-by-side result comparison
  • Code Generator: Shows current settings as executable code
  • Multi-format Download: Export results in various formats
  • Responsive Design: Optimized for desktop/tablet/mobile
  • Modern Material-UI 7.3: Clean, accessible interface
  • Dark/Light Theme: User preference support
  • WCAG 2.1 Compliance: Full accessibility standards

πŸš€ Running the Demo App

# Install all dependencies from root
pnpm install

# Start development server (recommended)
pnpm dev

# Or run individually
cd apps/exam
pnpm dev

🌐 Demo URL: http://localhost:3000

πŸ“± Tech Stack (2025 Latest)

Technology Version Purpose
React 19.1.1 Latest Concurrent Features
Next.js 15.5.4 App Router & SSR
Material-UI 7.3.x Modern component library
TypeScript 5.9.x Latest type system
Emotion 11.14.x CSS-in-JS styling
Chart.js 4.5.x Performance visualization

🎯 Learn by Example Patterns

// 1. Basic usage pattern
const handleImageProcess = async (file: File) => {
  const result = await processImage(file)
    .resize({ fit: 'cover', width: 800, height: 600 })
    .toBlob({ format: 'webp', quality: 0.8 });

  setProcessedImage(URL.createObjectURL(result.blob));
};

// 2. Advanced filter chain
const applyArtisticEffect = async (source: File) => {
  const processor = processImage(source);

  // Multiple effect combination
  const result = await processor
    .resize({ fit: 'cover', width: 1024, height: 1024 })
    .blur(1)
    .toBlob({ format: 'jpeg', quality: 0.9 });

  return result;
};

// 3. Batch processing pattern
const processBatch = async (files: File[]) => {
  const results = await Promise.all(
    files.map(file =>
      processImage(file)
        .resize({ fit: 'cover', width: 300, height: 300 })
        .toBlob({ format: 'webp' })
    )
  );

  return results;
};

πŸ—οΈ Monorepo Structure

web-image-util/
β”œβ”€β”€ πŸ“¦ sub/
β”‚   β”œβ”€β”€ web-image-util/          # 🎯 Main library package
β”‚   β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”‚   β”œβ”€β”€ index.ts         # Core API
β”‚   β”‚   β”‚   β”œβ”€β”€ advanced-index.ts # Advanced features
β”‚   β”‚   β”‚   β”œβ”€β”€ presets/         # Convenience functions
β”‚   β”‚   β”‚   β”œβ”€β”€ utils/           # Utilities
β”‚   β”‚   β”‚   β”œβ”€β”€ filters/         # Filter system
β”‚   β”‚   β”‚   └── composition/     # Image composition
β”‚   β”‚   β”œβ”€β”€ tests/               # 106 test cases
β”‚   β”‚   └── README.md            # πŸ“š Complete API documentation
β”‚   β”œβ”€β”€ eslint-config/           # Shared ESLint configuration
β”‚   └── typescript-config/       # Shared TypeScript configuration
β”œβ”€β”€ πŸ–₯️ apps/
β”‚   └── exam/                    # πŸ“± Next.js demo application
β”‚       β”œβ”€β”€ src/
β”‚       β”‚   β”œβ”€β”€ app/             # Next.js 15 App Router pages
β”‚       β”‚   β”œβ”€β”€ components/      # Shared UI components
β”‚       β”‚   └── hooks/           # Custom hooks
β”‚       β”œβ”€β”€ package.json
β”‚       └── README.md            # 🎨 UI development guide
β”œβ”€β”€ README.md                    # πŸ“– This file (project overview)
β”œβ”€β”€ package.json                 # Workspace configuration
└── turbo.json                   # Build pipeline configuration

πŸ› οΈ Development Guide

πŸ“‹ Development Commands

# πŸ—οΈ Build
pnpm build              # Build all packages
pnpm build:watch        # Build in watch mode

# πŸ§ͺ Testing
pnpm test               # Run all tests
pnpm test:coverage      # Run with coverage
pnpm test:ui            # Run in UI mode

# πŸ” Quality Checks
pnpm typecheck          # TypeScript type checking
pnpm lint               # ESLint linting
pnpm lint:fix           # Auto-fix linting errors
pnpm format             # Prettier formatting

# πŸš€ Development Server
pnpm dev                # Start demo app dev server

# πŸ“¦ Publishing
pnpm version:patch      # Patch version update
pnpm version:minor      # Minor version update
pnpm publish            # Publish to npm

🎯 Performance Targets

  • πŸ“Š Test Coverage: 90%+ overall
  • ⚑ Bundle Size: Main module < 50KB (gzipped)
  • πŸƒ Processing Speed: 1080p image < 500ms
  • πŸ’Ύ Memory Efficiency: Canvas pooling for memory reuse

🌐 Browser Support

Browser Min Version Key Features
Chrome 88+ WebP, OffscreenCanvas
Firefox 90+ WebP support
Safari 14+ WebP support
Edge 88+ Full support

Required APIs:

  • Canvas 2D Context βœ…
  • FileReader API βœ…
  • Blob/File API βœ…
  • Web Workers (performance boost) πŸ”§

πŸ“š Documentation

🌟 Key Technical Highlights

🎯 SVG Processing Excellence

Our SVG detection and processing logic is the technical crown jewel of this library:

  • Precise Detection: Advanced content sniffing beyond simple MIME type checking
  • Browser Compatibility: Automatic SVG enhancement for cross-browser support
  • Vector Preservation: High-quality SVG-to-canvas rendering pipeline
  • XSS Prevention: Security-focused SVG sanitization

⚑ Performance Engineering

  • Canvas Pooling: Reusable canvas instances for memory efficiency
  • Lazy Rendering: Deferred processing until final output
  • Smart Format Selection: Automatic WebP/AVIF fallback based on browser support
  • Memory Optimization: Intelligent cleanup and resource management

πŸ”’ Type Safety & DX

  • Discriminated Unions: Compile-time safety for resize configurations
  • Method Chaining: Intuitive chaining API design
  • Tree Shaking: ES modules for optimal bundle size
  • Zero Dependencies: Pure Canvas 2D API implementation

πŸ“Š Project Stats

  • πŸ“ Source Files: 65 TypeScript files
  • πŸ§ͺ Test Coverage: 12 comprehensive test suites
  • πŸ“¦ Current Version: v2.0.22
  • 🎯 TypeScript: 5.9+ with strict mode
  • ⚑ Build System: Turbo + tsup for optimal performance

πŸ“„ License

MIT License - see LICENSE file for details.

πŸ”— Links


Made with ❀️ for the web development community

About

Simple Web Image Utils

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •  

Languages