In order to apply filters and effects to an image in Go, you can utilize the built-in image and image/draw packages. Here's an example of applying the grayscale and sepia effects to an image:
import (
"image"
"image/color"
"image/jpeg"
"os"
)
file, err := os.Open("input.jpg")
if err != nil {
panic(err)
}
defer file.Close()
img, err := jpeg.Decode(file)
if err != nil {
panic(err)
}
bounds := img.Bounds()
newImg := image.NewRGBA(bounds)
func grayscale(c color.Color) color.Color {
r, g, b, _ := c.RGBA()
intensity := float64(r)/65535.0*0.2989 +
float64(g)/65535.0*0.5870 +
float64(b)/65535.0*0.1140
gray := uint16(intensity * 65535.0)
return color.RGBA64{gray, gray, gray, 65535}
}
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
oldColor := img.At(x, y)
newImg.Set(x, y, grayscale(oldColor))
}
}
func sepia(c color.Color) color.Color {
r, g, b, _ := c.RGBA()
newR := uint16(float64(r)/65535.0*0.393 +
float64(g)/65535.0*0.769 +
float64(b)/65535.0*0.189)
newG := uint16(float64(r)/65535.0*0.349 +
float64(g)/65535.0*0.686 +
float64(b)/65535.0*0.168)
newB := uint16(float64(r)/65535.0*0.272 +
float64(g)/65535.0*0.534 +
float64(b)/65535.0*0.131)
return color.RGBA64{newR, newG, newB, 65535}
}
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
oldColor := newImg.At(x, y)
newImg.Set(x, y, sepia(oldColor))
}
}
outputFile, err := os.Create("output.jpg")
if err != nil {
panic(err)
}
defer outputFile.Close()
jpeg.Encode(outputFile, newImg, nil)
This example demonstrates applying the grayscale and sepia effects to an input image. You can modify the functions to implement other filters or effects according to your requirements.