-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage.go
60 lines (50 loc) · 1.17 KB
/
image.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
package main
import (
"encoding/binary"
"errors"
"image"
"image/png"
"io"
"math"
"os"
)
func encodeBytesAsImage(bytes []byte) *image.RGBA {
binLength := make([]byte, 8)
binary.BigEndian.PutUint64(binLength, uint64(len(bytes)))
bytes = append(binLength, bytes...)
sideLength := int(math.Ceil(math.Sqrt(float64(len(bytes)) / 4)))
img := image.NewRGBA(image.Rect(0, 0, sideLength, sideLength))
copy(img.Pix, bytes)
return img
}
func originalBytesFromFile(name string) (bs []byte, err error) {
file, err := os.Open(name)
if err != nil {
return nil, err
}
defer file.Close()
return originalBytes(file)
}
func originalBytes(r io.Reader) (bs []byte, err error) {
img, err := png.Decode(r)
if err != nil {
return nil, err
}
nrgba, ok := img.(*image.NRGBA)
if !ok {
return nil, errors.New("failed to revert to original: expected NRGBA")
}
originalLength := binary.BigEndian.Uint64(nrgba.Pix[:8])
return nrgba.Pix[8 : originalLength+8], nil
}
func saveImage(name string, img *image.RGBA) error {
f, err := os.Create(name)
if err != nil {
return err
}
defer f.Close()
e := png.Encoder{
CompressionLevel: png.NoCompression,
}
return e.Encode(f, img)
}