-
Notifications
You must be signed in to change notification settings - Fork 1
/
pnmencoder.go
57 lines (51 loc) · 1.3 KB
/
pnmencoder.go
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
package pnm
import (
"bytes"
"fmt"
"io"
)
// Encoder encodes a pnm type image and writes it to a device
// the implements Writer interface
type Encoder struct {
writer io.Writer
}
// NewEncoder creates a new Encoder
func NewEncoder(writer io.Writer) *Encoder {
return &Encoder{writer}
}
// checkBinaryFormat checks if magic number is a binary format
func (e *Encoder) checkBinaryFormat(format int64) bool {
switch format {
case PPMBinary, PBMBinary, PGMBinary:
return true
default:
return false
}
}
// getHeader gets a formatted image header
func (e *Encoder) getHeader(mn, w, h int64, mv byte) string {
if mv > 1 {
return fmt.Sprintf("P%d\n%d %d\n%d\n", mn, w, h, mv)
}
return fmt.Sprintf("P%d\n%d %d\n", mn, w, h)
}
// Encode encodes image data to device
func (e *Encoder) Encode(image Image) error {
buffer := bytes.NewBuffer([]byte{})
buffer.WriteString(e.getHeader(image.MagicNumber(), image.Width(), image.Height(), image.Value()))
if e.checkBinaryFormat(image.MagicNumber()) {
_, err := buffer.Write(image.Buffer())
if err != nil {
return err
}
} else {
for _, b := range image.Buffer() {
_, err := buffer.WriteString(fmt.Sprintf("%d ", b))
if err != nil {
return err
}
}
}
io.Copy(e.writer, buffer)
return nil
}