Go - Creating Images

发布时间 2023-10-10 11:12:42作者: ZhangZhihuiAAA

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

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.