Search Unity

Pass NativeTexturePtr from unity to android java doesn't work

Discussion in 'Android' started by Bowie-Xu, Dec 14, 2018.

  1. Bowie-Xu

    Bowie-Xu

    Joined:
    Sep 14, 2011
    Posts:
    28
    Hi
    We are developing an app which needs to send unity WebCamTexture content to java gles. The current way is using GetPixels32() function, marshal copy to buffer and send it to java. It works fine but a little bit slow on low-end phones. Another way we are trying is to get texture's native ptr and send it to java side. Then using gles get color buffer.

    Codes as below:

    1. unity side, C# code
    private static AndroidJavaObject m_ColorGesture;
    m_ColorGesture = new AndroidJavaObject("com.xxxx.yyyy.zzzz", m_UnityActivity);
    m_ColorGesture.Call("UpdateImage", WebCamTexture.NativeTexturePtr().ToInt32(), WebCamTexture.Width, WebCamTexture.Height);

    2.android side, java code

    public void UpdateImage(int textureId, int imageWidth, int imageHeight)
    {

    if(bmp == null){
    bmp = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
    }
    ByteBuffer buffer = ByteBuffer.allocate(bmp.getByteCount());

    //int textures[] = new int[1];
    //GLES20.glGenTextures(1, textures, 0);
    //textures[0] = textureId;
    GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
    GLES20.glReadPixels(0, 0, imageWidth, imageHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buffer);
    bmp.copyPixelsFromBuffer(buffer);

    if(isSaveBmp == true && bmp != null) {
    SaveBmpToJpg(bmp, "/Captures/", "testimage" + new Date().getTime() + ".jpg");
    isSaveBmp = false;
    }
    }

    The content of saved jpg file is totally a mess. I looked it up on the internet and some said one reason is that unity are using multithread render and it causes the context used in gles is different with Unity. We also tried uncheck the "Multithreaded rendering" in playersettings without any luck.

    Is there anything we missed?

    Thanks in advance.