ZhangZhihui's Blog  

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.

 

posted on   ZhangZhihuiAAA  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
 
点击右上角即可分享
微信分享提示