Golan converts the original image [] byte to image.Image

Suppose I have an 8-bit grayscale image like this:

var pixels []byte = ... width := 100 height := 100 

How do I convert this to something that implements image.Image ?

+6
source share
1 answer

The image package has several image.Image implementations.

If you can find an implementation that models the pixels just like yours, you don’t need to do anything, just use this implementation.

For example, the image package has an image.Gray type that implements image.Image , and it models pixels with one byte being an 8-bit shade of gray.

So, if you have just that, just create an image.Gray and "tell it" value to use pixels :

 pixels := make([]byte, 100*100) // slice of your gray pixels, size of 100x100 img := image.NewGray(image.Rect(0, 0, 100, 100)) img.Pix = pixels 

Note No. 1:

Note that I used image.NewGray() , which returns the initialized value of image.Gray , so we only needed to set / change the pixel slice. Since image.Gray is a structure with exported fields, we could also create it by manually initializing all its fields:

 img := &image.Gray{Pix: pixels, Stride: 100, Rect: image.Rect(0, 0, 100, 100)} 

(Note that I used a pointer because only *image.Gray implements image.Image , because the methods are defined using the pointer's receiver. image.NewGray() also returns a pointer.)

Note # 2:

In our examples, we set the slice pixels to be used by the image. Now the image is attached to this fragment. If we change something, the pixel returned by Image.At() will also change (they use the same source). If you do not want this, you can copy the pixels to the Gray.Pix slice as follows:

 img := image.NewGray(image.Rect(0, 0, 100, 100)) copy(img.Pix, pixels) 

Try these examples on the Go Playground .

+5
source

All Articles