Created
August 27, 2018 14:27
-
-
Save campoy/42bee0dbe409dd8e6c94397b7d673b15 to your computer and use it in GitHub Desktop.
Creating mandelbrot, one pixel at a time
This file contains 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
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