forked from oaraujocesar/go-watermark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
91 lines (73 loc) · 2.17 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
package main
import (
"image"
"image/color"
"image/draw"
"image/jpeg"
"log"
"os"
"github.com/disintegration/imaging"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font"
"golang.org/x/image/font/gofont/goregular"
"golang.org/x/image/math/fixed"
)
func main() {
// Open the background image to add the watermark
img, err := imaging.Open("./assets/sample-1.jpeg")
if err != nil {
log.Fatalf("Failed to open: %s", err)
}
// image size
imgSize := img.Bounds().Size()
// create a string watermark with a name
watermark := createWatermark("Govind Kailas", imgSize.X, imgSize.Y)
// Add the overlay to the background image with 50% opacity
result := imaging.Overlay(img, watermark, image.Point{0, 0}, 0.5)
// Save the result image to file
thirdImage, err := os.Create("image-with-overlay.jpg")
if err != nil {
log.Fatalf("Failed to create: %s", err)
}
jpeg.Encode(thirdImage, result, &jpeg.Options{Quality: 100})
defer thirdImage.Close()
}
func createWatermark(name string, bgWidth, bgHeight int) *image.RGBA {
// Create a new RGBA image
img := image.NewRGBA(image.Rect(0, 0, bgWidth, bgHeight))
// Load the font and create a font face
fnt, err := truetype.Parse(goregular.TTF)
if err != nil {
panic(err)
}
// Create a font face with a proportional font size
face := truetype.NewFace(fnt, &truetype.Options{
Size: float64(bgWidth / 10),
})
// Calculate the width of the text using the font face
width := font.MeasureString(face, name).Round()
// Calculate the starting point of the text to center it
// This will render from right to left
startX := (img.Bounds().Dx() / 2) - width/2
// this will render from bottom to top
startY := (bgHeight / 2) + width/14
// Draw the text onto the image
col := color.RGBA{0, 0, 0, 128}
draw.Draw(img, img.Bounds(), image.NewUniform(col), image.Point{}, draw.Src)
watermark := &font.Drawer{
Dst: img,
Src: image.NewUniform(color.White),
Face: face,
Dot: fixed.P(startX, startY),
}
// text shadow
shadow := &font.Drawer{
Dst: img,
Src: image.NewUniform(color.Black),
Face: face,
Dot: fixed.P(startX+2, startY+2),
}
shadow.DrawString(name)
watermark.DrawString(name)
return img
}