forked from tiechui1994/gopdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
picture.go
96 lines (77 loc) · 1.75 KB
/
picture.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
package gopdf
import (
"image"
"image/color"
"image/draw"
"image/jpeg"
"image/png"
"os"
)
func GetImageType(picturePath string) (pictureType string, err error) {
_, err = os.Stat(picturePath)
if err != nil {
return "", err
}
fd, err := os.Open(picturePath)
if err != nil {
return "", err
}
_, pictureType, err = image.DecodeConfig(fd)
if err != nil {
return "", err
}
return pictureType, nil
}
func GetImageWidthAndHeight(picturePath string) (w, h int) {
var err error
_, err = os.Stat(picturePath)
if err != nil {
panic("the image path: " + picturePath + " not exist")
}
fd, err := os.Open(picturePath)
if err != nil {
panic("open image error")
}
config, _, err := image.DecodeConfig(fd)
if err != nil {
panic("decode image error")
}
return config.Width, config.Height
}
func ConvertPNG2JPEG(srcPath, dstPath string) (err error) {
srcFile, err := os.Open(srcPath)
if err != nil {
return
}
defer srcFile.Close()
srcImage, err := png.Decode(srcFile)
if err != nil {
return err
}
dstFile, err := os.Create(dstPath)
if err != nil {
return
}
defer dstFile.Close()
dstImage := image.NewRGBA(srcImage.Bounds())
draw.Draw(dstImage, dstImage.Bounds(), srcImage, srcImage.Bounds().Min, draw.Src)
return jpeg.Encode(dstFile, dstImage, nil)
}
func DrawPNG(srcPath string) {
const (
width = 300
height = 500
)
// 文件
pngFile, _ := os.Create(srcPath)
defer pngFile.Close()
// Image, 进行绘图操作
pngImage := image.NewRGBA(image.Rect(0, 0, width, height))
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
pngImage.Set(x, y, color.RGBA{uint8(256 % (x + 1)), uint8(y % 256), uint8((x ^ y) % 256), uint8((x ^ y) % 256)})
}
}
// 以png的格式写入文件
png.Encode(pngFile, pngImage)
}