Created
July 6, 2022 08:16
-
-
Save esimov/73b3e4484b000f6782ad6dce1c2e56bf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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