Select Git revision
fonticon2.py
sixel.go 11.58 KiB
package sixel
import (
"bufio"
"bytes"
"errors"
"fmt"
"image"
"image/color"
"image/draw"
"io"
"os"
"github.com/soniakeys/quant/median"
)
// Encoder encode image to sixel format
type Encoder struct {
w io.Writer
// Dither, if true, will dither the image when generating a paletted version
// using the Floyd–Steinberg dithering algorithm.
Dither bool
// Width is the maximum width to draw to.
Width int
// Height is the maximum height to draw to.
Height int
// Colors sets the number of colors for the encoder to quantize if needed.
// If the value is below 2 (e.g. the zero value), then 255 is used.
// A color is always reserved for alpha, so 2 colors give you 1 color.
Colors int
}
// NewEncoder return new instance of Encoder
func NewEncoder(w io.Writer) *Encoder {
return &Encoder{w: w}
}
const (
specialChNr = byte(0x6d)
specialChCr = byte(0x64)
)
// Encode do encoding
func (e *Encoder) Encode(img image.Image) error {
nc := e.Colors // (>= 2, 8bit, index 0 is reserved for transparent key color)
if nc < 2 {
nc = 255
}
width, height := img.Bounds().Dx(), img.Bounds().Dy()
if width == 0 || height == 0 {
return nil
}
if e.Width > 0 {
width = e.Width
}
if e.Height > 0 {
height = e.Height
}
var paletted *image.Paletted
// fast path for paletted images
if p, ok := img.(*image.Paletted); ok && len(p.Palette) < int(nc) {
paletted = p
} else {
// make adaptive palette using median cut alogrithm