Skip to content

Instantly share code, notes, and snippets.

@esimov
Created July 6, 2022 08:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esimov/73b3e4484b000f6782ad6dce1c2e56bf to your computer and use it in GitHub Desktop.
Save esimov/73b3e4484b000f6782ad6dce1c2e56bf to your computer and use it in GitHub Desktop.
// ImgToPix converts an image to an 1D uint8 pixel array.
// In order to preserve the color information per pixel we need to reconstruct the array to a specific format.
func ImgToPix(src *image.NRGBA) []uint8 {
size := src.Bounds().Size()
width, height := size.X, size.Y
pixels := make([][][3]uint8, height)
for y := 0; y < height; y++ {
row := make([][3]uint8, width)
for x := 0; x < width; x++ {
idx := (y*width + x) * 4
pix := src.Pix[idx : idx+4]
row[x] = [3]uint8{uint8(pix[0]), uint8(pix[1]), uint8(pix[2])}
}
pixels[y] = row
}
// Flatten the 3d array to 1D.
flattened := []uint8{}
for x := 0; x < len(pixels); x++ {
for y := 0; y < len(pixels[x]); y++ {
r := pixels[x][y][0]
g := pixels[x][y][1]
b := pixels[x][y][2]
flattened = append(flattened, r, g, b, 255)
}
}
return flattened
}
// PixToImage converts the pixel data to an image.
func PixToImage(pixels []uint8, rect image.Rectangle) image.Image {
img := image.NewNRGBA(rect)
bounds := img.Bounds()
dx, dy := bounds.Max.X, bounds.Max.Y
col := color.NRGBA{}
for y := bounds.Min.Y; y < dy; y++ {
for x := bounds.Min.X; x < dx*4; x += 4 {
col.R = pixels[x+y*dx*4]
col.G = pixels[x+y*dx*4+1]
col.B = pixels[x+y*dx*4+2]
col.A = pixels[x+y*dx*4+3]
img.SetNRGBA(int(x/4), y, col)
}
}
return img
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment