class="markdown_views prism-atom-one-light">
★ 练习题:操作 slice 显示图片
练习题位置:
https://tour.go-zh.org/moretypes/18
练习:切片
实现 Pic。它应当返回一个长度为 dy 的切片,其中每个元素是一个长度为 dx,元素类型为 uint8 的切片。当你运行此程序时,它会将每个整数解释为灰度值(好吧,其实是蓝度值)并显示它所对应的图像。
图像的选择由你来定。几个有趣的函数包括 (x+y)/2, x
y, x^y, xlog(y) 和 x%(y+1)。
(提示:需要使用循环来分配 [][]uint8 中的每个 []uint8;请使用 uint8(intValue) 在类型之间转换;你可能会用到 math 包中的函数。)
★ 代码
package main
import "golang.org/x/tour/pic"
func Pic(dx, dy int) [][]uint8 {
img := make([][]uint8, dy)
for i := 0; i < dx; i++ {
img[i] = make([]uint8, dx)
}
for i := 0; i < dy; i++ {
for j := 0; j < dx; j++ {
img[i][j] = (uint8)((i+j)/2)
}
}
return img
}
func main() {
pic.Show(Pic)
}
在网站上运行,显示效果为:
如果在命令行中运行,结果为:
注:我在cygwin中运行的。
$ ./slice02.exe
IMAGE:iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAIAAADTED8xAAADKElEQVR4nOzVoRHAMAzAQCfX/VduxjDQk8di+mb+mTlnyKB3vYBc9K4XkIs6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM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M6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANM6ANO+AAAA//9hKgMPVczXbQAAAABJRU5ErkJggg==" | base64.exe -d > pic.png
-
(i+j)/2
显示效果:
-
i*j
的显示效果:
-
i^j
的效果:
-
i*log(y)
的效果:
i*log(y)
,代码需要改成这样:
package main
import "golang.org/x/tour/pic"
import "math"
func Pic(dx, dy int) [][]uint8 {
img := make([][]uint8, dy)
for i := 0; i < dy; i++ {
img[i] = make([]uint8, dx)
}
for i := 0; i < dy; i++ {
for j := 0; j < dx; j++ {
img[i][j] = (uint8)(i*int(math.Log(float64(j))))
}
}
return img
}
func main() {
pic.Show(Pic)
}
i%(j+1)
的效果: