Problem: You want to create an image from scratch.
Solution: Create one of the Image implementation structs (e.g., NRGBA ) and populate it with the appropriate data.
As you remember from earlier, NRGBA has three attributes:
Pix
• A slice of bytes that contains the pixels in the image (it’s just a slice of color.Color )
Stride
• The distance between the two vertically adjacent pixels
Rect
• The dimensions of the image
package main import ( "crypto/rand" "image" "image/png" "log" "os" ) func main() { rect := image.Rect(0, 0, 100, 100) img := createRandomImage(rect) save("random.png", img) } func createRandomImage(rect image.Rectangle) (created *image.NRGBA) { pix := make([]uint8, rect.Dx()*rect.Dy()*4) rand.Read(pix) created = &image.NRGBA{ Pix: pix, Stride: rect.Dx() * 4, Rect: rect, } return }
Say you want to create an image that is 100 × 100 pixels. First, you need to create a Rect with the correct dimensions. Next, the Pix should be a slice of bytes of size 100 × 100 × 4 = 40,000 because each pixel is represented by 4 bytes (R, G, B, and A). Lastly, the Stride is the distance between two vertical pixels, which is the width of the image, multiplied by 4, which is 100 × 4 = 400.
The example code created a random image with each pixel a random color by populating the Pix slice of bytes with random bytes using rand.Read . You can fill it up with anything else, of course.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律