Skip to content

Instantly share code, notes, and snippets.

@peterhellberg
Created November 12, 2018 18:51
Show Gist options
  • Save peterhellberg/e6106b92bf17dbdd61d0c74801d4b8c1 to your computer and use it in GitHub Desktop.
Save peterhellberg/e6106b92bf17dbdd61d0c74801d4b8c1 to your computer and use it in GitHub Desktop.
16 bit gray scale image in Go
package main
import (
"image"
"image/color"
"image/png"
"os"
)
func main() {
w, h := 1200, 600
g := image.NewGray16(image.Rect(0, 0, w, h))
for x := 0; x < w; x++ {
for y := 0; y < h; y++ {
g.SetGray16(x, y, color.Gray16{uint16(x * y)})
}
}
if err := savePNG("/tmp/g16.png", g); err != nil {
panic(err)
}
}
func savePNG(fn string, m image.Image) error {
f, err := os.Create(fn)
if err != nil {
return err
}
defer f.Close()
return png.Encode(f, m)
}
@peterhellberg
Copy link
Author

g16

@peterhellberg
Copy link
Author

peterhellberg commented Nov 12, 2018

How an 8 bit gray scale image would look in comparison

package main

import (
	"image"
	"image/color"
	"image/png"
	"os"
)

func main() {
	w, h := 1200, 600

	g := image.NewGray(image.Rect(0, 0, w, h))

	for x := 0; x < w; x++ {
		for y := 0; y < h; y++ {
			g.SetGray(x, y, color.Gray{uint8(x * y)})
		}
	}

	if err := savePNG("/tmp/g8.png", g); err != nil {
		panic(err)
	}
}

func savePNG(fn string, m image.Image) error {
	f, err := os.Create(fn)
	if err != nil {
		return err
	}
	defer f.Close()

	return png.Encode(f, m)
}

g8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment