Skip to content

Instantly share code, notes, and snippets.

@campoy
Created Aug 27, 2018
Embed
What would you like to do?
Creating mandelbrot, one pixel at a time
package main
import (
"flag"
"image"
"image/color"
"image/png"
"log"
"os"
)
func main() {
width := flag.Int("width", 1024, "width of the image in pixels")
height := flag.Int("height", 1024, "height of the image in pixels")
out := flag.String("out", "out.png", "name for the output PNG file")
flag.Parse()
m := create(*width, *height)
f, err := os.Create(*out)
if err != nil {
log.Fatalf("could not create image: %v", err)
}
if err := png.Encode(f, m); err != nil {
log.Fatalf("could not encode image: %v", err)
}
if err := f.Close(); err != nil {
log.Fatalf("could not write file: %v", err)
}
}
func create(width, height int) image.Image {
m := image.NewRGBA(image.Rect(0, 0, width, height))
for i := 0; i < width; i++ {
for j := 0; j < height; j++ {
fillPixel(m, i, j)
}
}
return m
}
func fillPixel(m *image.RGBA, i, j int) {
b := m.Bounds()
// normalized from -2.5 to 1
xi := 3.5*float64(i)/float64(b.Dx()) - 2.5
// normalized from -1 to 1
yi := 2*float64(j)/float64(b.Dy()) - 1
const maxI = 1000
x, y := 0., 0.
for i := 0; (x*x+y*y < 4) && i < maxI; i++ {
x, y = x*x-y*y+xi, 2*x*y+yi
}
c := byte(x * y)
m.Set(i, j, &color.RGBA{c, c, c, 255})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment