[英]How to convert libGDX's Texture to byte array and back again in Java
所以我正在开发一个使用 libgdx 和 java 的小型多人游戏。 我正在使用数据报 sockets 和数据报包在客户端之间发送消息。 为了发送数据,我需要将其转换为字节数组。 我一直在寻找一种将 libgdx 纹理转换为字节数组的方法,但找不到解决方案。 我无法让 class 实现可序列化,因为我无法访问 class。
我将不胜感激任何帮助解决我的问题。 提前致谢!
您可以使用此答案中的以下代码段将您的Texture
转换为像素图:
Texture texture = textureRegion.getTexture();
if (!texture.getTextureData().isPrepared()) {
texture.getTextureData().prepare();
}
Pixmap pixmap = texture.getTextureData().consumePixmap();
获得Pixmap
后,您可以调用getPixels()
方法,该方法将返回一个ByteBuffer
,其中包括像素数据的字节数组。 您可以通过调用ByteBuffer
上的get(byte[])方法将原始数据读入byte[]
:
ByteBuffer byteBuffer = pixmap.getPixels();
byte[] pixelDataByteArray = new byte[byteBuffer.remaining()];
byteBuffer.get(pixelDataByteArray);
要将byte[]
转换回Texture
,您可以使用Pixmap
和Texture
的构造函数,如下所示:
Texture fromByteArray = new Texture(new Pixmap(pixelDataByteArray, 0, pixelDataByteArray.length));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.