Home > Back-end >  How to convert byte array to sensor_msgs.msg.CompressedImage in C#?
How to convert byte array to sensor_msgs.msg.CompressedImage in C#?

Time:11-04

I am trying to receive camera image from Unity and send it to ROS2 as an image message like sensor_msgs.msg.CompressedImage. In the part of TO DO:, I need to define a function to convert byte array to image messages. How should the ByteArrayToImage function to be?

```     Texture2D snapshot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false);
        snapCam.Render();
        RenderTexture.active = snapCam.targetTexture;
        snapshot.ReadPixels(new Rect(0,0,resWidth, resHeight), 0, 0);
        byte[] bytes = snapshot.EncodeToPNG();

        sensor_msgs.msg.CompressedImage ImageMsg = new sensor_msgs.msg.CompressedImage();

        // TO DO :  ImageMsg.Data = ByteArrayToImage(bytes);

        image_pub.Publish(ImageMsg); ``` 

CodePudding user response:

Have you checked the documentation for the libraries you are using?

Just going from this page about compressedImage, if you have a byte array containing a png encoded image you should just set it as the data, and specify the format:

ImageMsg.Data = bytes;
ImageMsg.Format = "png"

Note that I know nothing about either ROS2 nor Unity.

  • Related