image - Golang 将原始图像 []byte 转换为 image.Image

标签 image go

假设我有一个这样的 8 位灰度图像:

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

如何将其转换为实现 image.Image 的东西?

最佳答案

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/

相关文章:

ios - Swift 3 - 从图库中获取所有照片

jquery - 使用 jQuery .load() 回调和图像

ios - 在 iOS 中绘制到已加载的 UIImage

go - 如何禁止直接结构初始化

php - 使用 Laravel 5 intervention image 为图像添加空白以制作正方形图像

html - 设置 img src ="about:blank"是否有效?

nginx - 安全 websocket 的协议(protocol)是什么?

去嵌入 : method not inherited

go - Redshift 返回 []uint8 而不是整数,它们之间的转换返回不正确的值

html - Golang Martini 模板在渲染 Markdown 时只显示 HTML