问题描述
我想将内部png图像上传到后端,后端提供的API仅允许byte []数据上传.
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.
但是到目前为止,我还没有找到一种从纹理中提取byte []数据的方法.如果不是内部资源,我不确定是否要这样做?
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?
那么有什么方法可以使用Libgdx框架来实现呢?我要使用的图像已加载到AssetManager中.
So what ways are there to achieve this using Libgdx framework?The image I want to use is loaded with the AssetManager.
推荐答案
在尝试执行此操作之前,请确保了解以下内容:
Before trying to do this, make sure to understand the following:
A Texture
是驻留在视频内存(VRAM)中的OpenGL资源.纹理数据本身在RAM中不是(必需)可用的.因此,您不能直接访问它.将数据从VRAM传输到RAM相当于拍摄屏幕截图.通常,这是您要避免的事情.
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.
但是,如果使用AssetManager
加载图像,则是从文件加载图像,因此数据已经在RAM中可用.在这种情况下,它不被称为Texture
,而是被称为Pixmap
.从像素图获取数据的过程如下:
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();
请注意,您也可以使用AssetManager
加载Pixmap
(在这种情况下,您将使用unload
而不是dispose
). nativeData
包含原始内存,大多数API也可以使用该内存,因此请检查是否可以直接使用该内存.否则,您可以使用managedData
受管字节数组.
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.
这篇关于从Libgdx纹理中提取byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!