Skip to content

Instantly share code, notes, and snippets.

@NaniteFactory
Created December 13, 2018 06:37
Show Gist options
  • Select an option

  • Save NaniteFactory/828ac564a31bd7b43f52d9e74f0a8abb to your computer and use it in GitHub Desktop.

Select an option

Save NaniteFactory/828ac564a31bd7b43f52d9e74f0a8abb to your computer and use it in GitHub Desktop.
Get a single dimensional color.Color list (array) from an image.Image and vice versa.
func imageToColors(img image.Image) []color.Color {
rect := img.Bounds()
width := rect.Dx()
height := rect.Dy()
xFrom := rect.Min.X
xTo := rect.Max.X
yFrom := rect.Max.Y - 1
yTo := rect.Min.Y - 1
ret := make([]color.Color, width*height)
for y := yFrom; y > yTo; y-- {
for x := xFrom; x < xTo; x++ {
ret[((yFrom-y)*width)+x] = img.At(x, y)
}
}
return ret
}
func colorsToImage(colors []color.Color, width, height int) *image.NRGBA {
ret := image.NewNRGBA(image.Rect(0, 0, width, height))
for i, color := range colors {
col := i % width
row := (height - 1) - (i-col)/width
ret.Set(col, row, color)
}
return ret
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment