Extract byte[] from Libgdx Texture

2020-07-25 01:00发布

问题:

I want to upload an internal png image to my backend, the API supplied with the backend only allows for byte[] data to be uploaded.

But so far, I haven't found a way of extracting byte[] data from a texture. If it's an internal resource or not, I'm not sure matters?

So what ways are there to achieve this using Libgdx framework? The image I want to use is loaded with the AssetManager.

回答1:

Before trying to do this, make sure to understand the following:

A Texture is an OpenGL resource which resides in video memory (VRAM). The texture data itself is not (necessarily) available in RAM. So you can not access it directly. Transferring that data from VRAM to RAM is comparable to taking a screenshot. In general it is something you want to avoid.

However, if you load the image using AssetManager then you are loading it from file and thus have the data available in RAM already. In that case it is not called a Texture but a Pixmap instead. To get the data from the pixmap goes like this:

Pixmap pixmap = new Pixmap(Gdx.files.internal(filename));
ByteBuffer nativeData = pixmap.getPixels();
byte[] managedData = new byte[nativeData.remaining()];
nativeData.get(managedData);
pixmap.dispose();

Note that you can load the Pixmap using AssetManager as well (in that case you would unload instead of dispose it). The nativeData contains the raw memory, most API's can use that also, so check if you can use that directly. Otherwise you can use the managedData managed byte array.