0

So I'm working on a small multiplayer game using libgdx and java. I'm using datagram sockets and datagram packets to send messages between clients. In order to send data I need to convert it into a byte array. I've been searching to find a way to convert libgdx Textures to byte array but can't find the solution. I can't make the class implement Serializable since I have no access to the class.

I would greatly appreciate any help to fix my problem. Thanks in advance!

  • If you can't read it directly from texture try converting texture to Pixmap and read it from there. – MilanG Mar 29 '21 at 08:18

1 Answers1

2

You could convert your Texture into a Pixmap with the following snippet from this answer:

Texture texture = textureRegion.getTexture();
if (!texture.getTextureData().isPrepared()) {
    texture.getTextureData().prepare();
}
Pixmap pixmap = texture.getTextureData().consumePixmap();

When you have got the Pixmap you can call the getPixels() method which will return a ByteBuffer, that includes the byte array of pixel data. You can read the raw data into a byte[] by calling the get(byte[]) method on the ByteBuffer:

ByteBuffer byteBuffer = pixmap.getPixels();
byte[] pixelDataByteArray = new byte[byteBuffer.remaining()];
byteBuffer.get(pixelDataByteArray);

To convert the byte[] back to a Texture you can use the constructors of Pixmap and Texture like this:

Texture fromByteArray = new Texture(new Pixmap(pixelDataByteArray, 0, pixelDataByteArray.length));
Tobias
  • 2,547
  • 3
  • 14
  • 29
  • when I call the byteBuffer.array() java throws an Unsupported Operation Exception. Am I supposed to use a certain version of java? – Jimothy Cardotha Mar 29 '21 at 21:53
  • 1
    `ByteBuffer` is an abstract class in Java. This means there can be several implementations of it, and it seems that the `Pixmap` uses one that doesn't support the `array()` method. But instead of using the `array()` method you can also read the bytes to an array using the `get(byte[])` method like explained in [this answer](https://stackoverflow.com/a/28744228/8178842). I edited the answer accordingly. – Tobias Mar 30 '21 at 09:18