Adding a watermark to an image can be a useful technique to protect your images or brand them with a company logo. In this article, we will explore how you can achieve this using the Go programming language. We will utilize the "gocv" library, which is an OpenCV wrapper for Go, to manipulate images. Let's dive into the steps and see how you can add watermark text to your images.
1. Set Up Your Go Environment
First, ensure you have Go installed on your computer. You can download and install Go from its official website. Follow the instructions provided for your operating system to complete the installation.
2. Install Required Libraries
In order to manipulate images using Go, we'll need to install the "gocv" package. Open your terminal and run the following command:
go get -u -d gocv.io/x/gocvAdditionally, you'll need to have OpenCV installed on your system. Head over to the GoCV Getting Started page for detailed installation instructions for your specific operating system.
3. Load the Image
Create a new Go file. Let's create a function to load an image from a file:
package main
import (
"fmt"
"gocv.io/x/gocv"
)
func loadImage(filePath string) gocv.Mat {
img := gocv.IMRead(filePath, gocv.IMReadColor)
if img.Empty() {
fmt.Println("Error reading image")
}
return img
}
4. Add Watermark Text
Next, we need a function to overlay text onto an image. Here's how you can do it in Go using GoCV:
func addWatermark(image gocv.Mat, text string, x, y int) {
color := gocv.Scalar{Val1: 255, Val2: 255, Val3: 255, Val4: 0} // White color
scale := 1.5
thickness := 2
lineType := gocv.LineAA
gocv.PutText(&image, text, gocv.Point{X: x, Y: y}, gocv.FontHersheySimplex, scale, color, thickness, lineType)
}
5. Save the Modified Image
Finally, we need to save the modified image with the watermark back to your system:
func saveImage(filePath string, image gocv.Mat) {
if success := gocv.IMWrite(filePath, image); !success {
fmt.Println("Error saving image")
}
}
6. Main Function
Now let’s put everything together:
func main() {
imagePath := "path/to/your/image.jpg"
watermarkText := "Your Watermark Text"
outputPath := "path/to/save/watermarked_image.jpg"
// Load the image
img := loadImage(imagePath)
defer img.Close()
// Add the watermark
addWatermark(img, watermarkText, 50, 50) // You can adjust x and y according to your needs
// Save the result
saveImage(outputPath, img)
}Conclusion
In this article, we explored how to add a text watermark to an image using Go and the GoCV library. This helps in both personalizing and protecting the reuse of your images. For more advanced graphic manipulations, consider exploring additional features provided by OpenCV.