Skip to content

Instantly share code, notes, and snippets.

@jackmott
Created April 13, 2018 00:33
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 jackmott/1043789b1b96f3f5d7e177df99c5cb67 to your computer and use it in GitHub Desktop.
Save jackmott/1043789b1b96f3f5d7e177df99c5cb67 to your computer and use it in GitHub Desktop.
Golang img to sdl texture
func imgFileToTexture(renderer *sdl.Renderer, filename string) *sdl.Texture {
infile, err := os.Open(filename)
if err != nil {
panic(err)
}
defer infile.Close()
img, err := png.Decode(infile)
if err != nil {
panic(err)
}
w := img.Bounds().Max.X
h := img.Bounds().Max.Y
pixels := make([]byte, w*h*4)
bIndex := 0
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
r, g, b, a := img.At(x, y).RGBA()
pixels[bIndex] = byte(r / 256)
bIndex++
pixels[bIndex] = byte(g / 256)
bIndex++
pixels[bIndex] = byte(b / 256)
bIndex++
pixels[bIndex] = byte(a / 256)
bIndex++
}
}
tex := pixelsToTexture(renderer, pixels, w, h)
err = tex.SetBlendMode(sdl.BLENDMODE_BLEND)
if err != nil {
panic(err)
}
return tex
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment