最佳答案
image
包有几个 image.Image
的实现界面。
如果您能找到一个可以按照您所拥有的方式对像素进行建模的实现,那么您无需执行任何操作,只需使用该实现即可。
例如 image
包有一个 image.Gray
实现 image.Image
的类型,它以一个字节为 8 位灰度颜色对像素进行建模。
因此,如果您确实有这个,只需创建一个 image.Gray
的值并“告诉它”使用您的 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
注意事项 #1:
请注意,我使用了 image.NewGray()
它会返回一个初始化的 image.Gray
值,所以我们只需要设置/更改像素 slice 。由于 image.Gray
是一个带有导出字段的结构,我们也可以通过手动初始化它的所有字段来创建它:
img := &image.Gray{Pix: pixels, Stride: 100, Rect: image.Rect(0, 0, 100, 100)}
(请注意,我使用了指针,因为只有 *image.Gray
实现了 image.Image
,因为方法是用指针接收器定义的。image.NewGray()
也返回一个指针。)
注意 #2:
在我们的示例中,我们设置了图像使用的 pixels
slice 。图像现在绑定(bind)到这个 slice 。如果我们更改其中的任何内容,Image.At()
返回的像素也会更改(它们使用相同的源)。如果你不想要这个,你可以像这样将像素复制到 Gray.Pix
slice 中:
img := image.NewGray(image.Rect(0, 0, 100, 100))
copy(img.Pix, pixels)
在 Go Playground 上尝试这些示例.
关于image - Golang 将原始图像 []byte 转换为 image.Image,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38438444/