-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
115 lines (84 loc) · 2.41 KB
/
main.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
108
109
110
111
112
113
114
115
package main
import (
"image"
"image/color"
"image/draw"
"image/jpeg"
"image/png"
"os"
"github.com/noelyahan/impexp"
"github.com/noelyahan/mergi"
"golang.org/x/image/webp"
)
func main() {
Png2jpg("./image/image.png", "./image.png.jpg")
Watermar("./image.png.jpg")
Webp2jpg("./image/image.webp", "./image.webp.jpg")
Watermar("./image.webp.jpg")
Watermar("./image/image.jpg")
}
func Webp2jpg(orignImage, newImage string) (err error) {
webpImgFile, err := os.Open(orignImage)
if err != nil {
return
}
defer webpImgFile.Close()
imgSrc, err := webp.Decode(webpImgFile)
if err != nil {
return
}
return convert2jpg(imgSrc, newImage)
}
func Png2jpg(orignImage, newImage string) (err error) {
pngImgFile, err := os.Open(orignImage)
if err != nil {
return
}
defer pngImgFile.Close()
imgSrc, err := png.Decode(pngImgFile)
if err != nil {
return
}
return convert2jpg(imgSrc, newImage)
}
func convert2jpg(imgSrc image.Image, pathImage string) (err error) {
// create a new Image with the same dimension of PNG image
newImg := image.NewRGBA(imgSrc.Bounds())
// we will use white background to replace PNG's transparent background
// you can change it to whichever color you want with
// a new color.RGBA{} and use image.NewUniform(color.RGBA{<fill in color>}) function
draw.Draw(newImg, newImg.Bounds(), &image.Uniform{color.White}, image.Point{}, draw.Src)
// paste image OVER to newImage
draw.Draw(newImg, newImg.Bounds(), imgSrc, imgSrc.Bounds().Min, draw.Over)
// create new out JPEG file
jpgImgFile, err := os.Create(pathImage)
if err != nil {
return
}
defer jpgImgFile.Close()
var opt jpeg.Options
opt.Quality = 80
// convert newImage to JPEG encoded byte and save to jpgImgFile
// with quality = 80
err = jpeg.Encode(jpgImgFile, newImg, &opt)
//err = jpeg.Encode(jpgImgFile, newImg, nil) -- use nil if ignore quality options
if err != nil {
return
}
return
}
func Watermar(orignImage string) {
img, err := mergi.Import(impexp.NewFileImporter(orignImage))
if err != nil {
return
}
w := img.Bounds().Max.X / 4
watermarkImage, _ := mergi.Import(impexp.NewFileImporter("./image/logo.png"))
newWatermarkImage, _ := mergi.Resize(watermarkImage, uint(w), uint(w))
opecWatermark, _ := mergi.Opacity(newWatermarkImage, 0.6)
res, err := mergi.Watermark(opecWatermark, img, image.Pt(20, 20))
if err != nil {
return
}
mergi.Export(impexp.NewFileExporter(res, orignImage))
}