简体   繁体   English

如何在 Java 中将 libGDX 的纹理转换为字节数组并再次返回

[英]How to convert libGDX's Texture to byte array and back again in Java

So I'm working on a small multiplayer game using libgdx and java.所以我正在开发一个使用 libgdx 和 java 的小型多人游戏。 I'm using datagram sockets and datagram packets to send messages between clients.我正在使用数据报 sockets 和数据报包在客户端之间发送消息。 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.我一直在寻找一种将 libgdx 纹理转换为字节数组的方法,但找不到解决方案。 I can't make the class implement Serializable since I have no access to the class.我无法让 class 实现可序列化,因为我无法访问 class。

I would greatly appreciate any help to fix my problem.我将不胜感激任何帮助解决我的问题。 Thanks in advance!提前致谢!

You could convert your Texture into a Pixmap with the following snippet from this answer :您可以使用此答案中的以下代码段将您的Texture转换为像素图:

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.获得Pixmap后,您可以调用getPixels()方法,该方法将返回一个ByteBuffer ,其中包括像素数据的字节数组。 You can read the raw data into a byte[] by calling the get(byte[]) method on the ByteBuffer :您可以通过调用ByteBuffer上的get(byte[])方法将原始数据读入byte[]

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:要将byte[]转换回Texture ,您可以使用PixmapTexture的构造函数,如下所示:

Texture fromByteArray = new Texture(new Pixmap(pixelDataByteArray, 0, pixelDataByteArray.length));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM