How to apply filters and effects (e.g., grayscale, sepia) to an image in Go?

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:

  1. Import the required packages:
import ( "image" "image/color" "image/jpeg" "os" )
  1. Load the image file (assuming it's a JPEG in this example):
file, err := os.Open("input.jpg") if err != nil { panic(err) } defer file.Close() img, err := jpeg.Decode(file) if err != nil { panic(err) }
  1. Create a new image with the same dimensions as the loaded image:
bounds := img.Bounds() newImg := image.NewRGBA(bounds)
  1. Define the grayscale function to convert a color to grayscale:
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} }
  1. Apply the grayscale effect to the new image:
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)) } }
  1. Define the sepia function to convert a color to sepia:
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} }
  1. Apply the sepia effect to the new image:
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)) } }
  1. Save the modified image as another JPEG file:
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.