Convert Color32 array to byte array to send over network

陌路散爱 提交于 2019-12-11 02:29:10

问题


I have been working on webcam streaming for video and photo capture on Android devices within Unity3D. Most of the examples I have found in order to capture webcam feeds use a specific WebCamTexture object in order to get access to the devices camera hardware. I currently am able to capture the camera input but the WebCamTexture stores the data as a Color32[]. I found this solution below for converting a Color32[] to a byte[] but it seems to be swapping the red and blue color channels.

https://stackoverflow.com/a/21575147/8115962

Is there a way to prevent the red and blue channels from being reversed?


回答1:


Here is another way to Convert Color32 array from WebCamTexture to byte array:

First, create a structure to hold the converted array:

[StructLayout(LayoutKind.Explicit)]
public struct Color32Array
{
    [FieldOffset(0)]
    public byte[] byteArray;

    [FieldOffset(0)]
    public Color32[] colors;
}

The WebCamTexture to convert:

WebCamTexture webcamTex = new WebCamTexture();

Create new instance of that structure:

Color32Array colorArray = new Color32Array();

Initialize Color32 with the appropriate size:

colorArray.colors = new Color32[webcamTex.width * webcamTex.height];

Fill Color32 which automatically fills byte array:

webcamTex.GetPixels32(colorArray.colors);

Now, you can use colorArray.byteArray which is byte array.

Load into Texture 2D if needed:

Texture2D tex = new Texture2D(2, 2);
tex.LoadRawTextureData(colorArray.byteArray);
tex.Apply();

Like I said in my comment, it's better to convert the WebCamTexture to Texture2D then to jpeg or png then send it over the network. That will reduce the size of the image. See this answer for more information.



来源:https://stackoverflow.com/questions/47575438/convert-color32-array-to-byte-array-to-send-over-network

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!