1:解决的问题
Android获取unity 中Texture的纹理数据。尝试过传递参数的方式解决问题,发现效率太低。目前解决方案是传递texture纹理指针,Android 通过纹理指针绑定,然后获取纹理数据。
2:注意的问题
unity需要关闭多线程渲染.
3:关键代码
unity
/// <summary>
/// 设置共享纹理ID
/// Android 端需要调用
/// </summary>
/// <param name="ptr"></param>
/// <param name="w"></param>
/// <param name="h"></param>
public static void SetPtr(long ptr, int w, int h)
{
mediapipeJavaBridge.CallStatic("SetNativeTexturePtr", ptr, w, h);
}
//获取图片数据
public static void DetectHandPose()
{
mediapipeJavaBridge.CallStatic("DetectImg");
}
Java
//绑定纹理指针
public void BindTexture(int textureID1, int w, int h) {
unityContext = EGL14.eglGetCurrentContext();
unityDisplay = EGL14.eglGetCurrentDisplay();
if (unityContext == EGL14.EGL_NO_CONTEXT) {
Log.e(TAG, "UnityEGLContext is invalid -> Most probably wrong thread");
}
textureID = textureID1;
textureH = h;
textureW = w;
GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
int error1;
while ((error1 = GLES31.glGetError()) != GLES31.GL_NO_ERROR) {
Log.e(TAG, "OpenGL ES error11: " + error1);
}
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, textureID);
// TestSavePng();
}
///获取纹理
public Bitmap GetCurBitmap()
{
int width = textureW;// 纹理宽度
int height = textureH; // 纹理高度
int[] framebuffer = new int[1];
GLES31.glGenFramebuffers(1, framebuffer, 0);
GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, framebuffer[0]);
// Log.d(TAG, "TestSavePng: "+textureID);
// 将纹理对象附加到 FBO 的颜色附件上
GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, textureID, 0);
int error2;
while ((error2 = GLES31.glGetError()) != GLES31.GL_NO_ERROR) {
Log.e(TAG, "OpenGL ES error: " + error2);
}
// 检查帧缓冲完整性
int status = GLES31.glCheckFramebufferStatus(GLES31.GL_FRAMEBUFFER);
if (status != GLES31.GL_FRAMEBUFFER_COMPLETE) {
// 处理帧缓冲不完整的情况
Log.d(TAG, "TestSavePng: "+status);
}
// 读取像素数据
ByteBuffer pixelBuffer = ByteBuffer.allocateDirect(width * height * 4);
GLES31.glReadPixels(0, 0, width, height, GLES31.GL_RGBA, GLES31.GL_UNSIGNED_BYTE, pixelBuffer);
// Log.d(TAG, "initSurface: ");
// 现在,pixelBuffer 中包含了纹理的像素数据,你可以从中读取和处理像素数据
// 解绑帧缓冲对象
GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, 0);
// 创建一个 Bitmap 对象并设置像素数据
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(pixelBuffer);
pixelBuffer.clear();
pixelBuffer=null;
return bitmap;
}
本文介绍了如何在Unity中通过传递Texture指针来提高从Android获取Texture数据的效率,同时强调了关闭多线程渲染的重要性,并提供了关键代码片段,包括设置共享纹理ID、绑定纹理和获取纹理数据的步骤。

4358

被折叠的 条评论
为什么被折叠?



