How to add Watermark or Merge two image in Golang?

51 min read

To add a watermark or merge two images in Golang, you can use the github.com/disintegration/imaging package. Here's an example of how to do it:

package main

import (
	"fmt"
	"github.com/disintegration/imaging"
	"image"
	"image/draw"
	"os"
)

func main() {
	// Open the original image
	img, err := imaging.Open("original.jpg")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	// Open the watermark image
	watermark, err := imaging.Open("watermark.png")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	// Create a new RGBA image with the same dimensions as the original image
	result := imaging.New(img.Bounds().Max.X, img.Bounds().Max.Y, color.NRGBA{0, 0, 0, 0})

	// Copy the original image to the result image
	draw.Draw(result, result.Bounds(), img, image.Point{0, 0}, draw.Src)

	// Resize the watermark image to a specific size
	watermark = imaging.Resize(watermark, 100, 0, imaging.Lanczos)

	// Calculate the position to place the watermark image on the result image
	x := result.Bounds().Max.X - watermark.Bounds().Max.X - 10
	y := result.Bounds().Max.Y - watermark.Bounds().Max.Y - 10

	// Overlay the watermark image on the result image
	result = imaging.Overlay(result, watermark, image.Pt(x, y), 1.0)

	// Save the result image
	err = imaging.Save(result, "merged.jpg")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Println("Merged image saved as merged.jpg")
}

This example assumes you have two image files named original.jpg and watermark.png in the same directory as your Go file. Make sure to replace these file names with the actual file names you want to use.

First, it opens the original and watermark images using imaging.Open(). Then, it creates a new RGBA image with the same dimensions as the original image using imaging.New().

Next, it copies the original image to the result image using draw.Draw().

After that, it resizes the watermark image to a specific size using imaging.Resize().

Then, it calculates the position to place the watermark image on the result image.

Finally, it overlays the watermark image on the result image using imaging.Overlay(). The resulting image is saved to a file using imaging.Save().

Make sure to import the required packages and handle any errors that may occur during the process.