paintbrush

package module
v0.0.0-...-b7ad996 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 28, 2024 License: MIT Imports: 11 Imported by: 2

README

ANSI Paintbrush

ANSI Paintbrush allows you to convert images into colorful ASCII art using ANSI escape codes. It provides a simple interface for loading images, rendering them as ASCII art, and outputting the result in various formats.

Example

Example Output

Features

  • Convert images to ASCII art with ANSI color codes
  • Load custom TTF fonts for character selection
  • Adjustable output width and height with constraint handling
  • Multi-threaded rendering for improved performance
  • Multiple output formats (raw string, C-style string, Bash command)
  • Weighting and adding specific characters
  • Ability to exclude specific characters entirely
Future Plans

I'm always looking to improve ANSI Paintbrush. Some features being considering for future releases include:

  • Constraint behaviour options (stretch, center, etc.)
  • Command-line argument handling
  • Rendering the result to file

Usage

Installation
go get github.com/jordanella/go-ansi-paintbrush
Quickstart
package main

import (
    "fmt"
	_ "image/png"

    "github.com/jordanella/go-ansi-paintbrush"
)

func main() {
    // Create a new AnsiArt instance
    canvas := paintbrush.New()

    // Load an image
    err := canvas.LoadImage("examples/norman.png")
	if err != nil {
		fmt.Println(err)
		return
	}

	// Start the rendering process
	canvas.Paint()

    // Print the result
    fmt.Printf("\r%s", canvas.Result)
}

Note that it is important to include the appropriate file type support necessary for your project.

import (
    _ "image/png" // PNG support example
)

Canvas Reference

Type

The Canvas struct is the core of the ANSI Paintbrush library. It contains all the necessary fields for image processing, rendering, and output generation.

type Canvas struct {
    // Input and Rendering Configuration
    Font                Font              // Font used for rendering
    Image               image.Image       // Input image to be processed
    Width               int               // Output width in characters
    Height              int               // Output height in characters
    AspectRatio         float64           // Aspect ratio for output
    GlyphWidth          int               // Width of each glyph
    GlyphHeight         int               // Height of each glyph
    RuneStart           int               // Starting Unicode code point for character selection
    RuneLimit           int               // Ending Unicode code point for character selection
    Threads             int               // Number of threads for parallel processing
    ForbiddenCharacters map[rune]struct{} // Characters to exclude from rendering
    Weights             map[rune]float64  // Custom weights for character selection

    // Output Results
    Result       string         // Raw output string
    ResultC      string         // C-style string output
    ResultBash   string         // Bash command string output
    ResultRGBABytes []byte      // RGBA byte slice of the rendered image
    ResultRGBAWidth int         // Width of the RGBA output
    ResultRGBAHeight int        // Height of the RGBA output

    // Internal State
    Progress     float32        // Current progress of rendering (0.0 to 1.0)
    mu           sync.Mutex     // Mutex for thread-safe operations
}
Methods

The Canvas struct provides the following methods. For detailed documentation on each method, please refer to the inline comments in the source code or visit the GoDoc documentation.

Initialization
  • New() *Canvas
Input and Rendering Configuration
  • LoadFont(path string) error
  • SetFont(data []byte) error
  • LoadImage(path string) error
  • SetImage(img image.Image)
  • GetImage() image.Image
  • SetThreads(int)
  • SetWidth(int)
  • SetHeight(int)
  • AddForbiddenCharacter(rune)
  • RemoveForbiddenCharacter(rune)
  • ClearForbiddenCharacters()
  • GetForbiddenCharacters() []rune
  • IsForbiddenCharacter(rune) bool
  • SetAspectRatio(float64)
  • GetAspectRatio() float64
  • SetGlyphDimensions(width, height int)
  • GetGlyphDimensions() (width, height int)
  • SetRuneLimits(start, end int)
  • GetRuneLimits() (start, end int)
  • SetWeights(map[rune]float64)
  • AddWeights(map[rune]float64)
Rendering Process
  • Paint()
  • StartPainting()
  • GetProgress() float32
Output Retrieval
  • GetResult() string
  • GetResultC() string
  • GetResultBash() string
  • GetResultRGBABytes() []byte
  • GetResultRGBADimensions() (width, height int)

Character Weighting and Extended Characters

The ANSI Paintbrush library allows you to customize the character selection process through a weighting system. Weightings can be leveraged to emphasize certain characters over others or to add entirely new characters to the rendering process. This flexibility allows you to fine-tune the output to achieve the desired aesthetic for your images.

Characters with higher weights (closer to 1.0) are more likely to be chosen during the rendering process. The default weight for all characters is 1.0. Any specific characters will also be added to the pool of available characters for rendering, with the corresponding weights.

Note: Characters with weights set to 0 or negative values will be excluded from the rendering process entirely.

Setting Weights

You can set weights for characters using the SetWeights method, which replaces the entire existing weight map:

weights := map[rune]float64{
    '█': 0.95,
    '▓': 0.90,
    '▒': 0.85,
    '░': 0.80,
    '●': 0.75,
}
canvas.SetWeights(weights)
Adding or Updating Weights

To add new weights or update existing ones without affecting other characters, use the AddWeights method:

newWeights := map[rune]float64{
    '♥': 0.9,
    '♦': 0.9,
    '▓': 0.95, // This will update the existing weight for '▓'
}
canvas.AddWeights(newWeights)

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License.

Acknowledgements

This project is a Go fork of the original C++ ANSI Art library created by Marek Rogalski. I am very grateful for their work, which served as the foundation for this Go implementation.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var EmbeddedFonts embed.FS
View Source
var FiraMonoRegular = "assets/FiraMono-Regular.ttf"

Functions

This section is empty.

Types

type Canvas

type Canvas struct {
	// Input and Rendering Configuration
	Font                Font              // Font used for rendering
	Image               image.Image       // Input image to be processed
	Width               int               // Output width in characters
	Height              int               // Output height in characters
	AspectRatio         float64           // Aspect ratio for output
	GlyphWidth          int               // Width of each glyph
	GlyphHeight         int               // Height of each glyph
	RuneStart           int               // Starting Unicode code point for character selection
	RuneLimit           int               // Ending Unicode code point for character selection
	Threads             int               // Number of threads for parallel processing
	ForbiddenCharacters map[rune]struct{} // Characters to exclude from rendering
	Weights             map[rune]float64  // Custom weights for character selection

	// Output Results
	Result           string // Raw output string
	ResultC          string // C-style string output
	ResultBash       string // Bash command string output
	ResultRGBABytes  []byte // RGBA byte slice of the rendered image
	ResultRGBAWidth  int    // Width of the RGBA output
	ResultRGBAHeight int    // Height of the RGBA output

	// Internal State
	Progress float32 // Current progress of rendering (0.0 to 1.0)
	// contains filtered or unexported fields
}

func New

func New() *Canvas

New creates and returns a new Canvas instance with default settings.

func (*Canvas) AddForbiddenCharacter

func (c *Canvas) AddForbiddenCharacter(char rune)

AddForbiddenCharacter adds a character to the list of forbidden characters.

func (*Canvas) AddWeights

func (c *Canvas) AddWeights(weights map[rune]float64)

AddWeights adds the provided weights to the existing weight map. If a character already has a weight, it will be updated with the new value.

func (*Canvas) ClearForbiddenCharacters

func (c *Canvas) ClearForbiddenCharacters()

ClearForbiddenCharacters removes all characters from the list of forbidden characters.

func (*Canvas) GetAspectRatio

func (c *Canvas) GetAspectRatio() float64

GetAspectRatio returns the current aspect ratio.

func (*Canvas) GetForbiddenCharacters

func (c *Canvas) GetForbiddenCharacters() []rune

GetForbiddenCharacters returns a slice of all forbidden characters.

func (*Canvas) GetGlyphDimensions

func (c *Canvas) GetGlyphDimensions() (width, height int)

GetGlyphDimensions returns the current width and height of glyphs.

func (*Canvas) GetImage

func (c *Canvas) GetImage() image.Image

GetImage returns the currently set image.

func (*Canvas) GetProgress

func (c *Canvas) GetProgress() float32

GetProgress returns the current progress of the painting process.

func (*Canvas) GetResult

func (c *Canvas) GetResult() string

GetResult returns the raw result string without any formatting.

func (*Canvas) GetResultBash

func (c *Canvas) GetResultBash() string

GetResultBash returns the result as a Bash command string.

func (*Canvas) GetResultC

func (c *Canvas) GetResultC() string

GetResultC returns the result as a C-style string.

func (*Canvas) GetResultRGBABytes

func (c *Canvas) GetResultRGBABytes() []byte

GetResultRGBABytes returns the result as RGBA bytes.

func (*Canvas) GetResultRGBADimensions

func (c *Canvas) GetResultRGBADimensions() (width, height int)

GetResultRGBADimensions returns the width and height of the RGBA result.

func (*Canvas) GetRuneLimits

func (c *Canvas) GetRuneLimits() (int, int)

GetRuneLimits returns the current start and end rune limits.

func (*Canvas) IsForbiddenCharacter

func (c *Canvas) IsForbiddenCharacter(char rune) bool

IsForbiddenCharacter checks if a character is in the list of forbidden characters.

func (*Canvas) LoadFont

func (c *Canvas) LoadFont(path string) error

LoadFont loads a font from the specified file path.

func (*Canvas) LoadImage

func (c *Canvas) LoadImage(path string) error

LoadImage loads an image from the specified file path.

func (*Canvas) Paint

func (c *Canvas) Paint()

Paint performs the synchronous painting process.

func (*Canvas) RemoveForbiddenCharacter

func (c *Canvas) RemoveForbiddenCharacter(char rune)

RemoveForbiddenCharacter removes a character from the list of forbidden characters.

func (*Canvas) SetAspectRatio

func (c *Canvas) SetAspectRatio(ratio float64)

SetAspectRatio sets the aspect ratio for the output.

func (*Canvas) SetFont

func (c *Canvas) SetFont(data []byte) error

SetFont sets the font using the provided byte slice of font data.

func (*Canvas) SetGlyphDimensions

func (c *Canvas) SetGlyphDimensions(width, height int)

SetGlyphDimensions sets the width and height of glyphs.

func (*Canvas) SetHeight

func (c *Canvas) SetHeight(height int)

SetHeight sets the height of the output in characters.

func (*Canvas) SetImage

func (c *Canvas) SetImage(img image.Image)

SetImage sets the image to be rendered.

func (*Canvas) SetRuneLimits

func (c *Canvas) SetRuneLimits(start, end int)

SetRuneLimits sets the start and end rune limits for character selection.

func (*Canvas) SetThreads

func (c *Canvas) SetThreads(threads int)

SetThreads sets the number of threads to use for rendering.

func (*Canvas) SetWeights

func (c *Canvas) SetWeights(weights map[rune]float64)

SetWeights sets the weights for characters used in rendering.

func (*Canvas) SetWidth

func (c *Canvas) SetWidth(width int)

SetWidth sets the width of the output in characters.

func (*Canvas) StartPainting

func (c *Canvas) StartPainting()

StartPainting begins the asynchronous painting process.

type Font

type Font struct {
	GlyphHeight int
	GlyphWidth  int
	Aspect      float64
	Glyphs      map[rune]Glyph
}

type Glyph

type Glyph struct {
	Unicode int
	UTF8    string
	Pixels  []uint8
	Weight  float64
}

type Pixel

type Pixel struct {
	R, G, B, A uint8
}

func (Pixel) AnsiBg

func (p Pixel) AnsiBg() string

func (Pixel) AnsiColor

func (p Pixel) AnsiColor() string

func (Pixel) AnsiFg

func (p Pixel) AnsiFg() string

type Task

type Task struct {
	CharX, CharY int
}

type TaskResult

type TaskResult struct {
	CharX, CharY int
	Fg, Bg       Vec4
	Glyph        *Glyph
}

type Vec4

type Vec4 struct {
	R, G, B, A float64
}

func (Vec4) Abs

func (v Vec4) Abs() Vec4

func (Vec4) Add

func (v Vec4) Add(other Vec4) Vec4

func (Vec4) Div

func (v Vec4) Div(f float64) Vec4

func (Vec4) Dot

func (v Vec4) Dot(other Vec4) float64

func (Vec4) Mul

func (v Vec4) Mul(f float64) Vec4

func (Vec4) Sub

func (v Vec4) Sub(other Vec4) Vec4

func (Vec4) Sum

func (v Vec4) Sum() float64

func (Vec4) ToPixel

func (v Vec4) ToPixel() Pixel

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL