Created
March 3, 2014 12:57
-
-
Save thenonameguy/9324409 to your computer and use it in GitHub Desktop.
Golang pretty prime image generator, example output: http://imgur.com/w2BXltB
This file contains hidden or 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" | |
"math" | |
"os" | |
) | |
type PiImage struct { | |
x, y int | |
} | |
func (p PiImage) ColorModel() color.Model { | |
return color.RGBAModel | |
} | |
func (p PiImage) Bounds() image.Rectangle { | |
return image.Rect(0, 0, p.x, p.y) | |
} | |
func (p PiImage) At(x, y int) color.Color { | |
n := (p.x * y) + x | |
if isPrime(n) { | |
return color.RGBA{colorize(x, p.x), colorize(y, p.y), 255, 255} | |
} | |
return color.Black | |
} | |
var picX, picY int | |
var filename string | |
func init() { | |
flag.IntVar(&picX, "x", 1024, "picture width") | |
flag.IntVar(&picY, "y", 768, "picture height") | |
flag.StringVar(&filename, "f", "prime.png", "output filename") | |
} | |
func main() { | |
flag.Parse() | |
img := PiImage{picX, picY} | |
file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0755) | |
if err != nil { | |
log.Fatalln("Failed to open", filename, " for writing:", err) | |
} | |
if err := png.Encode(file, img); err != nil { | |
log.Fatalln("Failed to write image:", err) | |
} | |
} | |
func isPrime(n int) bool { | |
sqrt := int(math.Sqrt(float64(n))) | |
for i := 2; i <= sqrt; i++ { | |
if n%i == 0 { | |
return false | |
} | |
} | |
return true | |
} | |
func colorize(value, space int) uint8 { | |
return uint8((float32(value) / float32(space)) * 255) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment