Convert Figma logo to code with AI

jankovicsandras logoimagetracerjs

Simple raster image tracer and vectorizer written in JavaScript.

1,271
168
1,271
2

Top Related Projects

12,644

Reproducing images with geometric primitives.

3,142

Raster to Vector Graphics Converter

26,312

stb single-file public domain libraries for C/C++

Quick Overview

ImageTracerJS is a raster image tracer and vectorizer library written in JavaScript. It converts raster images (PNG, JPG, etc.) to vector graphics (SVG) by tracing the shapes and colors in the image. This library can be used both in the browser and with Node.js.

Pros

  • Pure JavaScript implementation, making it easy to integrate into web projects
  • Supports both browser and Node.js environments
  • Offers various options for customizing the tracing process
  • Provides multiple output formats, including SVG and simplified SVG paths

Cons

  • May produce less accurate results compared to more advanced tracing tools
  • Performance can be slow for large or complex images
  • Limited documentation and examples
  • Not actively maintained (last update was in 2019)

Code Examples

  1. Basic usage in the browser:
ImageTracer.imageToSVG(
  'image.png',
  function(svgstr) { console.log(svgstr); },
  'posterized2'
);

This code traces an image file and outputs the resulting SVG as a string.

  1. Using custom options:
var options = {
  corsenabled: false,
  ltres: 1,
  qtres: 1,
  pathomit: 8,
  colorsampling: 2
};

ImageTracer.imageToSVG('image.jpg', function(svgstr) {
  document.getElementById('svgcontainer').innerHTML = svgstr;
}, options);

This example demonstrates how to use custom options to control the tracing process.

  1. Node.js usage:
var ImageTracer = require('imagetracerjs');
var fs = require('fs');

ImageTracer.imageToSVG('image.png', function(svgstring){
  fs.writeFile('output.svg', svgstring, function(err) {
    if (err) throw err;
    console.log('SVG file saved!');
  });
});

This code shows how to use ImageTracerJS in a Node.js environment to trace an image and save the resulting SVG to a file.

Getting Started

To use ImageTracerJS in your project:

  1. Install the library:

    npm install imagetracerjs
    
  2. In a browser environment, include the script:

    <script src="imagetracer_v1.2.6.js"></script>
    
  3. In Node.js, require the module:

    const ImageTracer = require('imagetracerjs');
    
  4. Use the imageToSVG function to trace an image:

    ImageTracer.imageToSVG('path/to/image.png', function(svgString) {
      console.log(svgString);
    });
    

Competitor Comparisons

12,644

Reproducing images with geometric primitives.

Pros of primitive

  • Creates artistic, abstract representations of images using geometric shapes
  • Offers multiple output formats (SVG, GIF, PNG)
  • Provides fine-grained control over the number and types of shapes used

Cons of primitive

  • Slower processing time, especially for complex images
  • May require more manual tweaking to achieve desired results
  • Limited to geometric primitives (triangles, rectangles, ellipses, etc.)

Code comparison

primitive:

func DrawCircle(im *image.RGBA, x, y, r int, c color.Color) {
    for dy := -r; dy <= r; dy++ {
        for dx := -r; dx <= r; dx++ {
            if dx*dx+dy*dy <= r*r {
                im.Set(x+dx, y+dy, c)
            }
        }
    }
}

imagetracerjs:

function pathscan(arr, pathomit){
    var paths = [], pacnt = 0, pcnt = 0, px = 0, py = 0;
    for(var j=0; j<arr.length; j++){
        if(arr[j] && (pcnt = arr[j].length) > pathomit){
            paths[pacnt] = {};
            paths[pacnt].points = [];
            paths[pacnt].boundingbox = [1000000,1000000,0,0];
            paths[pacnt].holechildren = [];
            px = arr[j][0].x; py = arr[j][0].y;
            paths[pacnt].points.push({x:px,y:py});
            // ... (additional code omitted for brevity)
        }
    }
    return paths;
}

Both repositories offer image processing capabilities, but primitive focuses on creating abstract representations using geometric shapes, while imagetracerjs specializes in vectorization and tracing of raster images. The code snippets demonstrate the different approaches: primitive uses Go to draw shapes, while imagetracerjs employs JavaScript for path scanning and vectorization.

3,142

Raster to Vector Graphics Converter

Pros of vtracer

  • Written in Rust, offering better performance and memory safety
  • Supports multiple output formats including SVG, PDF, and DXF
  • Provides a command-line interface for easy integration into workflows

Cons of vtracer

  • Requires Rust runtime or compilation, which may be less accessible for some users
  • Less extensive documentation compared to imagetracerjs
  • Fewer configuration options for fine-tuning the tracing process

Code Comparison

imagetracerjs:

ImageTracer.imageToSVG(
  'image.png',
  function(svgstr) { console.log(svgstr); },
  { ltres: 0.1, qtres: 1, pathomit: 8 }
);

vtracer:

let mut tracer = Tracer::new();
tracer.set_input_path("image.png");
tracer.set_output_path("output.svg");
tracer.set_mode(Mode::Polygon);
tracer.run();

Both libraries offer image tracing functionality, but vtracer provides a more performant solution with broader output format support. However, imagetracerjs may be easier to integrate into web-based projects and offers more granular control over the tracing process. The choice between the two depends on specific project requirements and the development environment.

26,312

stb single-file public domain libraries for C/C++

Pros of stb

  • Comprehensive collection of single-file libraries for various tasks
  • Widely used and battle-tested in many projects
  • Supports multiple programming languages (C, C++)

Cons of stb

  • Larger codebase and potentially more complex to integrate
  • May include unnecessary functionality for specific use cases
  • Less focused on image tracing compared to imagetracerjs

Code Comparison

imagetracerjs:

ImageTracer.imageToSVG('image.png', function(svgstr) {
  console.log(svgstr);
});

stb:

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

int width, height, channels;
unsigned char *img = stbi_load("image.png", &width, &height, &channels, 0);

Key Differences

  • imagetracerjs is specifically designed for image tracing and SVG conversion
  • stb provides a broader set of image processing utilities
  • imagetracerjs is JavaScript-based, while stb is primarily for C/C++
  • stb offers more low-level control over image manipulation
  • imagetracerjs has a simpler API for quick tracing tasks

Both libraries have their strengths, with imagetracerjs being more specialized for image tracing and SVG output, while stb offers a wider range of image processing capabilities in a single-file format.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

imagetracerjs

alt Bitmap to Svg

Simple raster image tracer and vectorizer written in JavaScript.


Table of contents


Getting started

Using in the Browser

Include the script:

<script src="imagetracer_v1.2.6.js"></script>

Then:

// Loading an image, tracing with the 'posterized2' option preset, and appending the SVG to an element with id="svgcontainer"
ImageTracer.imageToSVG(

	'panda.png', /* input filename / URL */
	
	function(svgstr){ ImageTracer.appendSVGString( svgstr, 'svgcontainer' ); }, /* callback function to run on SVG string result */
	
	'posterized2' /* Option preset */
	
);

Using with Node.js

Node.js Command line interface example:

imagetracerjs/nodecli>node nodecli ../panda.png outfilename panda.svg scale 10

Expected result:

imagetracerjs/nodecli/panda.svg was saved!

News

1.2.6

  • NEW: InkScape extension
  • FIXED: hole shape parent search (Issues #31 #39)
  • FIXED: Handle (absolute) paths in CLI correctly Issue #42

1.2.5

  • RGBA ImageData check in colorquantization(), solving Issue #24 and #18

1.2.4

  • options.layering : default 0 = sequential, new method ; 1 = parallel, old method. (Enhancement Issue #17)
  • case insensitive option preset names
  • README.md reorganizing

Version history


API

Function nameArgumentsReturnsRun type
imageToSVGimage_url /*string*/ , callback /*function*/ , options /*optional object or preset name*/Nothing, callback(svgstring) will be executedAsynchronous, Browser only
imagedataToSVGimagedata /*object*/ , options /*optional object or preset name*/svgstring /*string*/Synchronous, Browser & Node.js
imageToTracedataimage_url /*string*/ , callback /*function*/ , options /*optional object or preset name*/Nothing, callback(tracedata) will be executedAsynchronous, Browser only
imagedataToTracedataimagedata /*object*/ , options /*optional object or preset name*/tracedata /*object*/Synchronous, Browser & Node.js

imagedata is standard ImageData here, canvas is canvas .

Helper Functions (Browser only)

Function nameArgumentsReturnsRun type
appendSVGStringsvgstring /*string*/, parentid /*string*/Nothing, an SVG will be appended to the container DOM element with id=parentid.Synchronous, Browser only
loadImageurl /*string*/, callback /*function*/Nothing, loading an image from a URL, then executing callback(canvas)Asynchronous, Browser only
getImgdatacanvas /*object*/imagedata /*object*/Synchronous, Browser only

imagedata is standard ImageData here, canvas is canvas . There are more functions for advanced users, read the source if you are interested. :)

"Browser only" means that Node.js doesn't have built-in canvas and DOM support as of 2018, so loading an image to an ImageData object needs an external library.


Options

You can use an option preset name (string) or an options object to control the tracing and rendering process.

Option presets gallery

These strings can be passed instead of the options object: 'default' 'posterized1' 'posterized2' 'posterized3' 'curvy' 'sharp' 'detailed' 'smoothed' 'grayscale' 'fixedpalette' 'randomsampling1' 'randomsampling2' 'artistic1' 'artistic2' 'artistic3' 'artistic4'

Read more about options.


Examples

Using in the Browser

Include the script:

<script src="imagetracer_v1.2.6.js"></script>

Then

// Loading smiley.png, tracing and calling alert callback on the SVG string result 
ImageTracer.imageToSVG( 'smiley.png', alert );


// Almost the same with options, and the ImageTracer.appendSVGString callback will append the SVG
ImageTracer.imageToSVG( 'smiley.png', ImageTracer.appendSVGString, { ltres:0.1, qtres:1, scale:10, strokewidth:5 } );


// This uses the 'posterized2' option preset and appends the SVG to an element with id="svgcontainer"
ImageTracer.imageToSVG(
	'panda.png',
	function(svgstr){ ImageTracer.appendSVGString( svgstr, 'svgcontainer' ); },
	'posterized2'
);


// The helper function loadImage() loads an image to a canvas, then executing callback:
// appending the canvas to a div here.
ImageTracer.loadImage(
	'panda.png',
	function(canvas){ (document.getElementById('canvascontainer')).appendChild(canvas); }
);


// ImageData can be traced to an SVG string synchronously.
ImageTracer.loadImage(
	'smiley.png',
	function(canvas){
	
		// Getting ImageData from canvas with the helper function getImgdata().
	 	var imgd = ImageTracer.getImgdata( canvas );
	 	
	 	// Synchronous tracing to SVG string
	 	var svgstr = ImageTracer.imagedataToSVG( imgd, { scale:5 } );
	 
	 	// Appending SVG
	 	ImageTracer.appendSVGString( svgstr, 'svgcontainer' );
	 	
	}
);


// This will load an image, trace it when loaded, and execute callback on the tracedata:
// stringifying and alerting it here.
ImageTracer.imageToTracedata(
	'smiley.png',
	function(tracedata){ alert( JSON.stringify( tracedata ) ); },
	{ ltres:0.1, qtres:1, scale:10 }
);


// imagedataToTracedata() is very similar to the previous functions. This returns tracedata synchronously.
ImageTracer.loadImage(
		'smiley.png',
		function(canvas){ 
		
			// Getting ImageData from canvas with the helper function getImgdata().
			var imgd = ImageTracer.getImgdata(canvas);
			
			// Synchronous tracing to tracedata
			var tracedata = ImageTracer.imagedataToTracedata( imgd, { ltres:1, qtres:0.01, scale:10 } );
			
			alert( JSON.stringify( tracedata ) );
		}
);

Using with Node.js CLI

Node.js Command line interface example:

imagetracerjs/nodecli>node nodecli ../panda.png outfilename panda.svg scale 10

Expected result:

imagetracerjs/nodecli/panda.svg was saved!

CLI parameter names are supported both with and without trailing dash: -scale 10 and scale 10 are both correct. Almost all options are supported, except pal and layercontainerid.

Simple Node.js converting example

"use strict";

var fs = require('fs');

var ImageTracer = require( __dirname + '/../imagetracer_v1.2.6' );

// This example uses https://github.com/arian/pngjs 
// , but other libraries can be used to load an image file to an ImageData object.
var PNGReader = require( __dirname + '/PNGReader' );

// Input and output filepaths / URLs
var infilepath = __dirname + '/' + 'panda.png';
var outfilepath = __dirname + '/' + 'panda.svg';


fs.readFile(
		
	infilepath,
	
	function( err, bytes ){ // fs.readFile callback
		if(err){ console.log(err); throw err; }
	
		var reader = new PNGReader(bytes);
	
		reader.parse( function( err, png ){ // PNGReader callback
			if(err){ console.log(err); throw err; }
			
			// creating an ImageData object
			var myImageData = { width:png.width, height:png.height, data:png.pixels };
			
			// tracing to SVG string
			var options = { scale: 5 }; // options object; option preset string can be used also
			
			var svgstring = ImageTracer.imagedataToSVG( myImageData, options );
			
			// writing to file
			fs.writeFile(
				outfilepath,
				svgstring,
				function(err){ if(err){ console.log(err); throw err; } console.log( outfilepath + ' was saved!' ); }
			);
			
		});// End of reader.parse()
		
	}// End of readFile callback()
	
);// End of fs.readFile()

Tracedata processing / Simplify.js example

It's possible to process the traced geometry and color data before SVG rendering. This example simplify_interop.html shows polyline simplification. You need to download simplify.js from https://github.com/mourner/simplify-js .


InkScape extension

ImageTracer is available as an InkScape extension: https://inkscape.org/~MarioVoigt/%E2%98%85imagetracerjs-for-inkscape-1x

Screenshots

Thanks Mario Voigt!


Process overview

See Process overview and Ideas for improvement


License

The Unlicense / PUBLIC DOMAIN

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.

In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to http://unlicense.org

NPM DownloadsLast 30 Days