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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With