| 1 |
|
| 2 |
package kitty |
| 3 |
|
| 4 |
import ( |
| 5 |
"compress/zlib" |
| 6 |
"fmt" |
| 7 |
"image" |
| 8 |
"image/color" |
| 9 |
"image/png" |
| 10 |
"io" |
| 11 |
) |
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
type Decoder struct { |
| 18 |
|
| 19 |
Decompress bool |
| 20 |
|
| 21 |
|
| 22 |
Format int |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
Width int |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
Height int |
| 31 |
} |
| 32 |
|
| 33 |
|
| 34 |
func (d *Decoder) Decode(r io.Reader) (image.Image, error) { |
| 35 |
if d.Decompress { |
| 36 |
zr, err := zlib.NewReader(r) |
| 37 |
if err != nil { |
| 38 |
return nil, fmt.Errorf("failed to create zlib reader: %w", err) |
| 39 |
} |
| 40 |
|
| 41 |
defer zr.Close() |
| 42 |
r = zr |
| 43 |
} |
| 44 |
|
| 45 |
if d.Format == 0 { |
| 46 |
d.Format = RGBA |
| 47 |
} |
| 48 |
|
| 49 |
switch d.Format { |
| 50 |
case RGBA, RGB: |
| 51 |
return d.decodeRGBA(r, d.Format == RGBA) |
| 52 |
|
| 53 |
case PNG: |
| 54 |
return png.Decode(r) |
| 55 |
|
| 56 |
default: |
| 57 |
return nil, fmt.Errorf("unsupported format: %d", d.Format) |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
|
| 62 |
func (d *Decoder) decodeRGBA(r io.Reader, alpha bool) (image.Image, error) { |
| 63 |
m := image.NewRGBA(image.Rect(0, 0, d.Width, d.Height)) |
| 64 |
|
| 65 |
var buf []byte |
| 66 |
if alpha { |
| 67 |
buf = make([]byte, 4) |
| 68 |
} else { |
| 69 |
buf = make([]byte, 3) |
| 70 |
} |
| 71 |
|
| 72 |
for y := range d.Height { |
| 73 |
for x := range d.Width { |
| 74 |
if _, err := io.ReadFull(r, buf[:]); err != nil { |
| 75 |
return nil, fmt.Errorf("failed to read pixel data: %w", err) |
| 76 |
} |
| 77 |
if alpha { |
| 78 |
m.SetRGBA(x, y, color.RGBA{buf[0], buf[1], buf[2], buf[3]}) |
| 79 |
} else { |
| 80 |
m.SetRGBA(x, y, color.RGBA{buf[0], buf[1], buf[2], 0xff}) |
| 81 |
} |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
return m, nil |
| 86 |
} |