如何在Go中将RGB字节切片转换为image.Image?

huangapple go评论81阅读模式
英文:

How do I convert an RGB byte[] slice to an image.Image in go?

问题

一个在另一个进程中运行的C++应用程序将一个由三字节像素(红色、绿色、蓝色)组成的char[]数组传递给一个Go程序。我已经使用cgo将其重构为一个byte[]切片,但我不确定如何转换为图像。如果需要的话,我也可以传递宽度或高度(我想这是必要的)。

我知道image.RGBA类型,但文档似乎暗示这些不仅仅是每个颜色一个字节,并且假设有一个alpha通道,而我的非常简单的位图没有这个通道。将我拥有的3个字节值转换为与image.RGBA兼容的值是否是一个解决方案?如果是,我应该如何做到这一点?

或者,我可以在将值转换为go识别的格式(jpeg、gif、png)之前在C/C++中进行转换。无论哪种方式都适用于我的用途,但我不知道如何处理其中任何一种方式。

英文:

A C++ application running in another process passes in a char[] array of three-byte pixels (red, green, blue) to a go program. I've reconstructed this in go as a byte[] slice using cgo, but I'm unsure how to convert to an image. I can pass the width or height as well, if that is needed (I would imagine it would be).

I'm aware of the image.RGBA type, but the documentation seems to imply that those aren't just single-byte-per-color, and that assumes that there is an alpha channel, which my very simplistic bitmap does not have. Would converting the 3 byte values I have into something that works with image.RGBA be a solution? If so, how should I do that?

Alternatively, I could do the conversion in C/C++ before sending the values into a format that go recognizes (jpeg, gif, png). Either way works for my uses, but I don't know how to approach either.

答案1

得分: 2

image 包是基于接口的。只需定义一个具有这些方法的新类型。

你的类型的 ColorModel 方法应返回 color.RGBAModelBounds 方法应返回你的矩形的边界,At 方法应返回在 (x, y) 处的颜色,如果你知道图像的尺寸,可以计算出该颜色。

英文:

The image package is based on interfaces. Just define a new type with those methods.

Your type's ColorModel would return color.RGBAModel, Bounds - your rectangle's borders, and At - the color at (x, y) that you can compute if you know the image's dimensions.

huangapple
  • 本文由 发表于 2015年4月1日 00:32:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/29373741.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定