npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@xbibzlibrary/imageconverter

v1.0.1

Published

Powerful and complete image converter to SVG, ICO, PNG with modern algorithms and optimal performance

Readme

🎨 @xbibzlibrary/imageconverter

Logo mmk

NPM Version License JavaScript



🌟 Features

// SVG - Advanced bitmap to vector conversion
✓ Potrace-inspired tracing algorithm
✓ Multi-color support with color quantization
✓ Path optimization & curve simplification
✓ Configurable threshold & tolerance

// ICO - Multi-size icon generation
✓ Supports 16x16 to 256x256 sizes
✓ PNG & BMP compression
✓ Anti-aliasing & aspect ratio preservation
✓ Windows-optimized output

// PNG - Advanced encoding & optimization
✓ Adaptive filtering (None, Sub, Up, Average, Paeth)
✓ Custom compression levels
✓ Dithering support (Floyd-Steinberg, Atkinson)
✓ Metadata stripping & palette optimization
✓ Potrace Tracing - Professional bitmap to vector conversion
✓ K-means Clustering - Intelligent color quantization
✓ Douglas-Peucker - Path simplification
✓ Floyd-Steinberg Dithering - High-quality color reduction
✓ Median Cut - Adaptive palette generation
✓ Bilateral Filtering - Edge-preserving noise reduction
✓ Web Workers - Parallel processing for batch operations
✓ Performance Monitoring - Real-time metrics tracking
✓ Memory Management - Efficient resource handling
✓ Progress Tracking - Session-based checkpoints

📦 Installation

NPM

npm install @xbibzlibrary/imageconverter

CDN

<script src="https://cdn.jsdelivr.net/npm/@xbibzlibrary/imageconverter"></script>

Yarn

yarn add @xbibzlibrary/imageconverter

Download

wget https://github.com/XbibzOfficial/imageconverter/releases/latest/download/imageconverter.min.js

🚀 Quick Start

Basic Usage

import ImageConverter from '@xbibzlibrary/imageconverter';

// Initialize converter
const converter = new ImageConverter();

// Convert image to SVG
const svg = await converter.toSVG('image.jpg');
console.log(svg); // <svg xmlns="http://www.w3.org/2000/svg">...</svg>

// Convert to ICO
const ico = await converter.toICO('logo.png');
const url = URL.createObjectURL(ico);
document.querySelector('link[rel="icon"]').href = url;

// Convert to PNG
const png = await converter.toPNG('photo.jpg', {
  compressionLevel: 9,
  adaptiveFiltering: true
});

🎨 Advanced SVG Conversion

// Professional bitmap to vector tracing
const svg = await converter.toSVG('artwork.jpg', {
  algorithm: 'potrace',           // Potrace tracing algorithm
  optimizePaths: true,            // Optimize SVG paths
  simplifyCurves: true,           // Simplify Bezier curves
  detectColors: true,             // Multi-color detection
  colorQuantization: 16,          // Number of colors
  threshold: 128,                 // Black/white threshold (0-255)
  turdSize: 2,                    // Minimum contour size
  alphaMax: 1.0,                  // Corner threshold
  optTolerance: 0.2,              // Curve optimization tolerance
  precision: 2                    // Decimal precision
});

// Result: High-quality scalable vector graphic
document.body.innerHTML = svg;

🖼️ ICO Multi-Size Generation

// Generate Windows-optimized favicon
const ico = await converter.toICO('logo.png', {
  sizes: [16, 32, 48, 64, 128, 256],  // All standard sizes
  compression: 'png',                  // 'png' or 'bmp'
  includeAllSizes: true,               // Include all sizes
  optimizeForWindows: true,            // Windows optimization
  enableAntiAliasing: true,            // Smooth scaling
  preserveAspectRatio: true            // Maintain proportions
});

// Save as favicon.ico
const blob = new Blob([ico], { type: 'image/x-icon' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'favicon.ico';
link.click();

🎯 PNG Optimization

// Maximum compression with adaptive filtering
const optimizedPng = await converter.toPNG('photo.jpg', {
  compressionLevel: 9,          // 0-9 (9 = maximum compression)
  adaptiveFiltering: true,      // Smart filter selection
  enableDithering: false,       // Color dithering
  colorType: 'truecolor',       // 'truecolor', 'grayscale', 'palette'
  bitDepth: 8,                  // 8 or 16 bits per channel
  
  // Post-processing
  postProcessing: {
    optimize: true              // Additional optimization
  }
});

// Result: Highly optimized PNG file

🎯 Advanced Usage

Batch Processing with Web Workers

const converter = new ImageConverter({
  enableWebWorkers: true,
  workerCount: 4  // Use 4 CPU cores
});

const images = ['img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg'];

// Process all images in parallel
const results = await converter.batchConvert(images, 'svg', {
  algorithm: 'potrace',
  detectColors: true
});

console.log(`Converted ${results.length} images`);

Image Analysis

// Get comprehensive image information
const info = await converter.getImageInfo('photo.jpg');

console.log(info);
/*
{
  basic: {
    width: 1920,
    height: 1080,
    aspectRatio: 1.778,
    pixelCount: 2073600
  },
  color: {
    dominantColors: [
      { rgb: [255, 100, 50], hex: '#ff6432', percentage: 45.2 },
      { rgb: [50, 100, 255], hex: '#3264ff', percentage: 30.1 }
    ],
    colorPalette: [...],
    averageColor: [150, 120, 90],
    brightness: 0.65,
    contrast: 0.82,
    saturation: 0.58
  },
  technical: {
    hasTransparency: true,
    entropy: 7.45,
    sharpness: 125.3,
    noiseLevel: 8.2,
    estimatedFileSize: 384000,
    compressionRatio: 0.185
  }
}
*/

Pre & Post Processing

const result = await converter.convert('image.jpg', 'svg', {
  // Pre-processing
  preProcessing: {
    resize: { width: 800, height: 600, algorithm: 'bicubic' },
    crop: { x: 100, y: 100, width: 600, height: 400 },
    rotate: { angle: 90, backgroundColor: '#ffffff' },
    filter: { 
      type: 'sharpen', 
      parameters: { strength: 1.5 } 
    }
  },
  
  // Conversion settings
  algorithm: 'potrace',
  detectColors: true,
  
  // Post-processing
  postProcessing: {
    optimize: true
  }
});

Performance Monitoring

const converter = new ImageConverter({
  enablePerformanceMonitoring: true,
  logLevel: 'info'
});

// Perform conversions...
await converter.toSVG('image1.jpg');
await converter.toICO('image2.png');

// Get performance statistics
const stats = converter.getPerformanceStats();
console.log(stats);
/*
{
  operations: {
    conversion: {
      count: 2,
      totalDuration: 1250,
      minDuration: 580,
      maxDuration: 670,
      avgDuration: 625,
      recentAvg: 625
    }
  },
  summary: {
    totalOperations: 2,
    totalDuration: 1250,
    avgDuration: 625
  },
  activeSessions: 0
}
*/

📚 API Reference

Constructor

new ImageConverter(options?)

| Option | Type | Default | Description | |--------|------|---------|-------------| | logLevel | string | 'info' | Logging level: 'debug', 'info', 'warn', 'error' | | enableWebWorkers | boolean | true | Enable Web Workers for parallel processing | | workerCount | number | navigator.hardwareConcurrency | Number of Web Workers | | enablePerformanceMonitoring | boolean | true | Track performance metrics | | enableAdvancedOptimization | boolean | true | Enable advanced optimizations |

Methods

convert(input, format, options?)

Generic conversion method.

Parameters:

  • input: string | File | Blob | HTMLImageElement | HTMLCanvasElement
  • format: 'svg' | 'ico' | 'png'
  • options: object (format-specific options)

Returns: Promise<string | Blob>


toSVG(input, options?)

Convert to SVG with Potrace tracing.

interface SVGOptions {
  algorithm?: 'potrace';                    // Tracing algorithm
  optimizePaths?: boolean;                  // Optimize SVG paths
  simplifyCurves?: boolean;                 // Simplify curves
  detectColors?: boolean;                   // Multi-color detection
  colorQuantization?: number;               // Number of colors (2-256)
  threshold?: number;                       // Black/white threshold (0-255)
  turdSize?: number;                        // Min contour size (pixels)
  alphaMax?: number;                        // Corner threshold (0-1.33)
  optTolerance?: number;                    // Curve tolerance (0-1)
  precision?: number;                       // Decimal places (0-10)
}

Example:

const svg = await converter.toSVG('artwork.jpg', {
  algorithm: 'potrace',
  detectColors: true,
  colorQuantization: 16,
  threshold: 128,
  optimizePaths: true
});

toICO(input, options?)

Generate multi-size ICO file.

interface ICOOptions {
  sizes?: number[];              // Icon sizes [16, 32, 48, 64, 128, 256]
  compression?: 'png' | 'bmp';   // Compression format
  includeAllSizes?: boolean;     // Include all sizes
  optimizeForWindows?: boolean;  // Windows optimization
  enableAntiAliasing?: boolean;  // Anti-aliasing
  preserveAspectRatio?: boolean; // Aspect ratio preservation
}

Example:

const ico = await converter.toICO('logo.png', {
  sizes: [16, 32, 48],
  compression: 'png',
  optimizeForWindows: true
});

toPNG(input, options?)

Convert to optimized PNG.

interface PNGOptions {
  compressionLevel?: number;     // 0-9 (9 = max compression)
  adaptiveFiltering?: boolean;   // Adaptive filter selection
  enableDithering?: boolean;     // Enable dithering
  colorType?: string;            // 'truecolor', 'grayscale', 'palette'
  bitDepth?: number;             // 8 or 16
}

Example:

const png = await converter.toPNG('photo.jpg', {
  compressionLevel: 9,
  adaptiveFiltering: true
});

batchConvert(inputs, format, options?)

Batch process multiple images.

Parameters:

  • inputs: Array<string | File | Blob>
  • format: 'svg' | 'ico' | 'png'
  • options: object (conversion options)

Returns: Promise<Array<string | Blob>>

Example:

const results = await converter.batchConvert(
  ['img1.jpg', 'img2.jpg', 'img3.jpg'],
  'svg',
  { algorithm: 'potrace' }
);

getImageInfo(input)

Get comprehensive image analysis.

Returns: Promise<ImageInfo>

interface ImageInfo {
  basic: {
    width: number;
    height: number;
    aspectRatio: number;
    pixelCount: number;
  };
  color: {
    dominantColors: Array<{rgb: number[], hex: string, percentage: number}>;
    colorPalette: Array<{rgb: number[], hex: string}>;
    colorHistogram: {red: number[], green: number[], blue: number[]};
    averageColor: number[];
    brightness: number;
    contrast: number;
    saturation: number;
  };
  technical: {
    hasTransparency: boolean;
    estimatedFileSize: number;
    compressionRatio: number;
    entropy: number;
    sharpness: number;
    noiseLevel: number;
  };
  metadata: object;
}

🎨 Image Filters

Built-in filters for pre-processing:

await converter.convert('image.jpg', 'svg', {
  preProcessing: {
    filter: {
      type: 'grayscale' | 'sepia' | 'invert' | 'brightness' | 
            'contrast' | 'blur' | 'sharpen' | 'edge' | 'emboss' | 'vintage',
      parameters: {
        // Filter-specific parameters
        value: number,      // For brightness/contrast
        radius: number,     // For blur
        strength: number,   // For sharpen/emboss
        intensity: number   // For sepia/vintage
      }
    }
  }
});

🔧 Algorithms Explained

How it works:

  1. Bitmap to Binary: Convert image to black & white based on threshold
  2. Contour Detection: Find all closed contours in the binary image
  3. Path Optimization: Apply Douglas-Peucker simplification
  4. Curve Fitting: Fit Bezier curves to simplified paths
  5. SVG Generation: Convert optimized paths to SVG format

Parameters:

  • threshold: Controls black/white cutoff point
  • turdSize: Filters out tiny details
  • alphaMax: Adjusts corner smoothness
  • optTolerance: Controls path simplification aggressiveness

Algorithm steps:

  1. Sample pixels: Randomly sample image pixels
  2. Initialize centroids: Use k-means++ for optimal starting points
  3. Cluster assignment: Assign each pixel to nearest color
  4. Update centroids: Calculate new average colors
  5. Converge: Repeat until colors stabilize

Result: Reduced color palette for efficient multi-color SVG tracing

Filter types:

  • None: No filtering (fast, low compression)
  • Sub: Difference from left pixel
  • Up: Difference from above pixel
  • Average: Average of left and above
  • Paeth: Smart predictor algorithm

Adaptive filtering automatically selects the best filter for each scanline to maximize compression.


📊 Performance Tips

✅ Do

// Use Web Workers for batch processing
const converter = new ImageConverter({
  enableWebWorkers: true,
  workerCount: 4
});

// Resize before processing
preProcessing: {
  resize: { width: 800, height: 600 }
}

// Use appropriate color quantization
colorQuantization: 16  // Not too high

❌ Don't

// Don't process huge images
// Resize first!

// Don't use too many colors
colorQuantization: 256  // Slow!

// Don't disable optimization
enableAdvancedOptimization: false

// Don't ignore performance monitoring
enablePerformanceMonitoring: false

🌐 Browser Support


🤝 Contributing

Contributions are welcome! Please follow these steps:

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

📄 License

MIT © Xbibz Official


👨‍💻 Author

Author ganteng

Xbibz Official

Telegram TikTok Ko-fi

Support this project:

  • ⭐ Star this repository
  • 🐛 Report bugs and suggest features
  • 💰 Buy me a coffee

Made with ❤️ by Xbibz Official

Don't forget to give this project a star!