import ( "image" "image/color" "image/png" "os" ) func main() { width := 100 height := 100 palette := []color.Color{ color.Black, color.RGBA{255, 0, 0, 255}, color.RGBA{0, 255, 0, 255}, color.RGBA{0, 0, 255, 255}, } img := image.NewPaletted(image.Rect(0, 0, width, height), palette) // Draw something on the image... file, err := os.Create("output.png") if err != nil { panic(err) } defer file.Close() png.Encode(file, img) }
import ( "image" "image/color" "image/draw" "image/jpeg" "os" ) func main() { file, err := os.Open("input.jpg") if err != nil { panic(err) } defer file.Close() img, _, err := image.Decode(file) if err != nil { panic(err) } width := img.Bounds().Dx() height := img.Bounds().Dy() palette := []color.Color{ color.Black, color.RGBA{255, 0, 0, 255}, color.RGBA{0, 255, 0, 255}, color.RGBA{0, 0, 255, 255}, } paletted := image.NewPaletted(img.Bounds(), palette) draw.FloydSteinberg.Draw(paletted, img.Bounds(), img, image.ZP) file, err = os.Create("output.jpg") if err != nil { panic(err) } defer file.Close() jpeg.Encode(file, paletted, nil) }This code reads an existing JPEG image from a file and converts it to a paletted image using the Floyd-Steinberg dithering algorithm. The `image.Decode` function is used to read the image, and then the `draw.FloydSteinberg.Draw` function is used to convert it to a paletted image. The resulting image is written to a JPEG file using the `jpeg.Encode` function. Overall, the `image/paletted` package provides a simple way to work with paletted images in Go. It is part of the standard library and is well-documented.