Skip to content

Instantly share code, notes, and snippets.

@paulohrpinheiro
Created May 7, 2020 23:19
Show Gist options
  • Save paulohrpinheiro/2277c2500874ca4eb38f772f7c9ea568 to your computer and use it in GitHub Desktop.
Save paulohrpinheiro/2277c2500874ca4eb38f772f7c9ea568 to your computer and use it in GitHub Desktop.
A nice image
package main
import (
"image"
"image/color"
"image/png"
"math"
"os"
"sync"
)
const (
size = 1000
fileName = "somegraph.png"
maxColors = 255
leftX = -5.0
rightX = 5.0
topY = 3.0
bottomY = -3.0
)
var (
wg sync.WaitGroup
)
func makePalette() []color.Color {
palette := make([]color.Color, maxColors)
for i := 0; i < maxColors-1; i++ {
palette[i] = color.RGBA{uint8(i % 90), uint8(i % 90), uint8(i), maxColors}
}
palette[maxColors-1] = palette[0]
return palette
}
func plotLine(img *image.Paletted, x int, convertedX, convertedY, factorY float64) {
defer wg.Done()
for y := 0; y < size; y++ {
value := math.Pow(math.Pi * convertedX * math.Cos(convertedX * convertedY), 2)
paletteIndex := uint8(value) % maxColors
img.SetColorIndex(x, y, paletteIndex)
convertedY += factorY
}
}
func writeToFile(img *image.Paletted) {
f, createErr := os.Create(fileName)
if createErr != nil {
panic(createErr)
}
defer f.Close()
encodeErr := png.Encode(f, img)
if encodeErr != nil {
panic(encodeErr)
}
}
func main() {
palette := makePalette()
rect := image.Rect(0, 0, size, size)
img := image.NewPaletted(rect, palette)
factorX := (rightX - leftX) / float64(size)
factorY := (topY - bottomY) / float64(size)
convertedX := leftX
for x := 0; x < size; x++ {
convertedY := bottomY
wg.Add(1)
go plotLine(img, x, convertedX, convertedY, factorY)
convertedX += factorX
}
wg.Wait()
writeToFile(img)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment