In order to convert an image to grayscale or black-and-white in Go, you can make use of the github.com/disintegration/imaging
package. Here's an example code snippet that demonstrates how to achieve this:
package main
import (
"image"
"log"
"os"
"github.com/disintegration/imaging"
)
func main() {
// Open the image file
imageFile, err := os.Open("input.png")
if err != nil {
log.Fatalf("failed to open image: %v", err)
}
defer imageFile.Close()
// Decode the image file
inputImage, _, err := image.Decode(imageFile)
if err != nil {
log.Fatalf("failed to decode image: %v", err)
}
// Convert the image to grayscale
grayscaleImage := imaging.Grayscale(inputImage)
// Save the grayscale image to a file
err = imaging.Save(grayscaleImage, "output_grayscale.png")
if err != nil {
log.Fatalf("failed to save grayscale image: %v", err)
}
// Convert the image to black-and-white
blackAndWhiteImage := imaging.AdjustContrast(inputImage, -20) // Adjust contrast to get a better result
blackAndWhiteImage = imaging.Grayscale(blackAndWhiteImage)
// Save the black-and-white image to a file
err = imaging.Save(blackAndWhiteImage, "output_black_white.png")
if err != nil {
log.Fatalf("failed to save black-and-white image: %v", err)
}
}
Make sure to replace "input.png"
with the path to your input image file. This code converts the input image to grayscale using the imaging.Grayscale()
function and saves the result as "output_grayscale.png"
. Additionally, it converts the input image to black-and-white by adjusting the contrast with imaging.AdjustContrast()
and then applying grayscale conversion. The black-and-white image is saved as "output_black_white.png"
.
Remember to include the github.com/disintegration/imaging
package in your Go module by executing go get github.com/disintegration/imaging
before running the code.