1.生成灰度的曼德勃罗集图像代码示例,其中求根方程为y=x^2-1。
import (
"bufio"
"fmt"
"image"
"image/color"
"image/png"
"math/cmplx"
"os"
)
func main() {
const (
xmin, ymin, xmax, ymax = -2, -2, +2, +2
width, height = 2048, 2048
)
img := image.NewRGBA(image.Rect(0, 0, width, height))
// 使用image库返回image.Image接口的image.RGBA类型数据,width与height分别为新建图片的宽度和高度
for py := 0; py < height; py++ {
y := float64(py)/height*(ymax-ymin) + ymin // 转换为对应+2与-2区域的复平面点y坐标
for px := 0; px < width; px++ {
x := float64(px)/width*(xmax-xmin) + xmin // 转换为对应+2与-2区域的复平面点x坐标
z := complex(x, y) // Image point (px, py) represents complex value z.
img.Set(px, py, mandelbrot(z)) // 设置图片对应x,y坐标点的颜色
}
}
outFile, _ := os.Create("gopher3.png")
defer func(outFile *os.File) {
err := outFile.Close()
if err != nil {
panic(err)
}
}(outFile)
// 打开新建的png文件并在函数结束后释放该文件
// defer的使用方法:defer语句注册了一个函数调用,这个调用会延迟到defer语句所在的函数执行完毕后执行
b := bufio.NewWriter(outFile) // 将 b 封装成一个带缓存的 bufio.Writer 对象
err = png.Encode(b, img) // 将img文件编码为png格式并存放在b中
if err != nil {
panic(err)
}
err = b.Flush() // 将缓存中的所有数据写入底层的 io.Writer 对象中
if err != nil {
panic(err)
}
}
func mandelbrot(z complex128) color.Color { // color.Color为返回对象的类型,此处为type Color
const iterations = 200
const contrast = 15
var v complex128
for n := uint8(0); n < iterations; n++ {
v = v*v + z
if cmplx.Abs(v) > 2 {
return color.Gray{Y: 255 - contrast*n} // 对于发散点赋予对应的颜色(Gray)
}
}
return color.Black // 对于非发散点也赋予对应的颜色(Gray)
}
2.生成彩色的曼德勃罗集图像代码示例,其中求根方程为y=x^2-1,集内点的颜色使用RGB值为(100,149,237),即矢车菊的蓝色,代码详细注释略。
package main
import (
"bufio"
"image"
"image/color"
"image/png"
"math/cmplx"
"os"
)
func main() {
const (
xmin, ymin, xmax, ymax = -2, -2, +2, +2
width, height = 1024, 1024
)
img := image.NewNRGBA(image.Rect(0, 0, width, height))
for py := 0; py < height; py++ {
y := float64(py)/height*(ymax-ymin) + ymin
for px := 0; px < width; px++ {
x := float64(px)/width*(xmax-xmin) + xmin
z := complex(x, y) // Image point (px, py) represents complex value z.
img.SetNRGBA(px, py, mandelbrot(z))
}
}
outFile, _ := os.Create("gopher2.png")
defer func(outFile *os.File) {
err := outFile.Close()
if err != nil {
panic(err)
}
}(outFile)
b := bufio.NewWriter(outFile)
png.Encode(b, img)
b.Flush()
}
func mandelbrot(z complex128) color.NRGBA {
const iterations = 200
const contrast = 20
var v complex128
for n := uint8(0); n < iterations; n++ {
v = v*v + z
if cmplx.Abs(v) > 2 {
return color.NRGBA{R: 255, G: 255, B: 255, A: 255}
}
}
alpha := cmplx.Abs(v)
return color.NRGBA{R: 100, G: 149, B: 237, A: uint8(255 * alpha)}
}
运行代码,即可得到如下的效果图:
参考资料:《Go语言圣经》



