Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang convert raw image []byte to image.Image

Tags:

image

go

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

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

How do I convert that into something that implements image.Image?

like image 794
Timmmm Avatar asked Jul 18 '16 13:07

Timmmm


1 Answers

The image package has several implementations of the image.Image interface.

If you can find an implementation which models the pixels just as you have it, you don't need to do anything just use that implementation.

For example the image package has an image.Gray type which implements image.Image and it models the pixels with one byte being an 8-bit grayscale color.

So if you have exactly this, simply create a value of image.Gray and "tell it" to use your 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 #1:

Note that I used image.NewGray() which returns you an initialized value of image.Gray, so we only needed to set / change the pixels slice. Since image.Gray is a struct 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 as methods are defined with pointer receiver. image.NewGray() also returns a pointer.)

Note #2:

In our examples we set the pixels slice to be used by the image. The image is now bound to this slice. If we change anything in it, the pixel returned by Image.At() will also change (they use the same source). If you don't want this, you may copy the pixels to the Gray.Pix slice like this:

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

Try these examples on the Go Playground.

like image 120
icza Avatar answered Nov 08 '22 20:11

icza