forked from ftrvxmtrx/tga
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encode.go
107 lines (83 loc) · 2.37 KB
/
encode.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package tga
import (
"encoding/binary"
"errors"
"image"
"image/draw"
"io"
)
// Encode encodes an image into TARGA format.
func Encode(w io.Writer, m image.Image) (err error) {
b := m.Bounds()
mw, mh := b.Dx(), b.Dy()
h := rawHeader{
Width: uint16(mw),
Height: uint16(mh),
}
if int(h.Width) != mw || int(h.Height) != mh {
return errors.New("uint16 width/height overflow")
}
h.Flags = flagOriginTop
switch tm := m.(type) {
case *image.Gray:
h.ImageType = imageTypeMonoChrome
err = encodeGray(w, tm, h)
case *image.NRGBA:
h.ImageType = imageTypeTrueColor
err = encodeRGBA(w, tm, h, attrTypeAlpha)
case *image.RGBA:
h.ImageType = imageTypeTrueColor
err = encodeRGBA(w, (*image.NRGBA)(tm), h, attrTypePremultipliedAlpha)
default:
// convert to non-premultiplied alpha by default
h.ImageType = imageTypeTrueColor
newm := image.NewNRGBA(b)
draw.Draw(newm, b, m, b.Min, draw.Src)
err = encodeRGBA(w, newm, h, attrTypeAlpha)
}
return
}
func encodeGray(w io.Writer, m *image.Gray, h rawHeader) (err error) {
h.BPP = 8 // 8-bit monochrome
if err = binary.Write(w, binary.LittleEndian, &h); err != nil {
return
}
offset := -(m.Rect.Min.Y*m.Stride + m.Rect.Min.X)
max := offset + int(h.Height)*m.Stride
for ; offset < max; offset += m.Stride {
if _, err = w.Write(m.Pix[offset : offset+int(h.Width)]); err != nil {
return
}
}
// no extension area, only a footer
err = binary.Write(w, binary.LittleEndian, newFooter())
return
}
func encodeRGBA(w io.Writer, m *image.NRGBA, h rawHeader, attrType byte) (err error) {
h.BPP = 32 // always save as 32-bit (faster this way)
h.Flags |= 8 // 8-bit alpha channel
if err = binary.Write(w, binary.LittleEndian, &h); err != nil {
return
}
lineSize := int(h.Width) * 4
offset := -m.Rect.Min.Y*m.Stride - m.Rect.Min.X*4
max := offset + int(h.Height)*m.Stride
b := make([]byte, lineSize)
for ; offset < max; offset += m.Stride {
copy(b, m.Pix[offset:offset+lineSize])
for i := 0; i < lineSize; i += 4 {
b[i+0], b[i+2] = b[i+2], b[i+0] // RGBA -> BGRA
}
if _, err = w.Write(b); err != nil {
return
}
}
// add extension area and footer to define attribute type
if _, err = w.Write(newExtArea(attrType)); err != nil {
return
}
footer := newFooter()
footer.ExtAreaOffset = uint32(tgaRawHeaderSize + int(h.Height)*lineSize)
err = binary.Write(w, binary.LittleEndian, footer)
return
}