-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpng.go
59 lines (54 loc) · 1.25 KB
/
png.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
package examples
import (
"image"
"image/png"
"os"
"github.com/sebnyberg/imgcrop/bmpx"
"golang.org/x/image/bmp"
)
// cropPNG is not part of the library because it does not meet its memory
// requirements. Converting PNG to BMP and back does a full in-memory
// serialization twice. Why even include this example? Because it shows how
// ineffecient this method is.
func cropPNG(srcPath, dstPath string, region image.Rectangle) error {
// Decode PNG, encode BMP to temporary file
src, err := os.OpenFile(srcPath, os.O_RDONLY, 0)
if err != nil {
return err
}
defer src.Close()
tmpSrcBMP, err := os.CreateTemp("", "")
if err != nil {
return err
}
defer tmpSrcBMP.Close()
img, err := png.Decode(src)
if err != nil {
return err
}
err = bmp.Encode(tmpSrcBMP, img)
if err != nil {
return err
}
// Create temporary cropped BMP output file and crop to it
tmpDstBMP, err := os.CreateTemp("", "")
if err != nil {
return err
}
defer tmpDstBMP.Close()
err = bmpx.Crop(src, tmpDstBMP, region)
if err != nil {
return err
}
// Encode BMP back to PNG
dst, err := os.OpenFile(dstPath, os.O_WRONLY, 0640)
if err != nil {
return err
}
defer dst.Close()
img, err = bmp.Decode(tmpDstBMP)
if err != nil {
return err
}
return png.Encode(dst, img)
}