-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencode.go
More file actions
76 lines (67 loc) · 1.87 KB
/
encode.go
File metadata and controls
76 lines (67 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package xtx
import (
"image"
"io"
)
// Encode writes img to w in XTG or XTH format.
//
// The target format is determined by:
// 1. If img is [*Monochrome], encodes as XTG (skips conversion).
// 2. If img is [*Grayscale], encodes as XTH (skips conversion).
// 3. Otherwise, uses opts.Format (default [FormatMonochrome]).
//
// When opts.Ditherer is provided and the source requires conversion,
// it is used to dither the image into the target color space.
//
// A nil opts is equivalent to &Options{Format: FormatMonochrome}.
func Encode(w io.Writer, img image.Image, opts *Options) error {
if opts == nil {
opts = &Options{}
}
switch src := img.(type) {
case *Monochrome:
return encodeRaw(w, src.Rect.Dx(), src.Rect.Dy(), MagicXTG, src.Pix)
case *Grayscale:
return encodeRaw(w, src.Rect.Dx(), src.Rect.Dy(), MagicXTH, src.Pix)
}
bounds := img.Bounds()
width, height := bounds.Dx(), bounds.Dy()
if width == 0 || height == 0 {
return ErrDimensionZero
}
if width > 65535 || height > 65535 {
return ErrDimensionOverflow
}
ditherer := opts.Ditherer
if ditherer == nil {
ditherer = DitherNone
}
var mark uint32
var pix []byte
if opts.Format == FormatGrayscale {
gray := NewGrayscale(image.Rect(0, 0, width, height))
ditherer.Draw(gray, gray.Bounds(), img, bounds.Min)
mark = MagicXTH
pix = gray.Pix
} else {
mono := NewMonochrome(image.Rect(0, 0, width, height))
ditherer.Draw(mono, mono.Bounds(), img, bounds.Min)
mark = MagicXTG
pix = mono.Pix
}
return encodeRaw(w, width, height, mark, pix)
}
// encodeRaw writes the header and pixel data for XTG or XTH.
func encodeRaw(w io.Writer, width, height int, mark uint32, pix []byte) error {
h := &Header{
Mark: mark,
Width: uint16(width),
Height: uint16(height),
DataSize: uint32(len(pix)),
}
if _, err := h.WriteTo(w); err != nil {
return err
}
_, err := w.Write(pix)
return err
}