Converting Android Bitmap to LibGdx's Texture

烈酒焚心 提交于 2019-11-27 14:53:55

hmm another possibility is that you've got a threading issue. I've noticed this kind of problem when loading my own unmanaged textures on the UI thread while libgdx is doing its thing loading textures concurrently on the render thread. If this is the problem the simple solution is to synchronize the creation of the texture with the render thread using Gdx.app.postRunnable. i.e.:

public void onByteArrayOfCroppedImageReciever(byte[] bytes) {
    try {
        pmap=new Pixmap(bytes, 0, bytes.length);
        Gdx.app.postRunnable(new Runnable() {
            @Override
            public void run() {            
                tex=new Texture(pmap);
                face=new Sprite(tex);
            }
        });
    } catch(Exception e) {
        Gdx.app.log("KS", e.toString());
        e.printStackTrace();
    }
}

If the goal is to convert an Android Bitmap to a libgdx Texture, you don't need to use Pixmap at all. You can do it directly with the help of simple OpenGL and Android GLUtils. Try the followings; it is 100x faster than your solution. I assume that you are not in the rendering thread (you should not most likely). If you are, you don't need to call postRunnable().

       Gdx.app.postRunnable(new Runnable() {
        @Override
        public void run() {
          Texture tex = new Texture(bitmap.getWidth(), bitmap.getHeight(), Format.RGBA8888);
          GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tex.getTextureObjectHandle());
          GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
          GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
          bitmap.recycle();
          // now you have the texture to do whatever you want
        }
      });

you have to code on a new thread because pixmap class takes time for byte conversion and sometimes returns a temporary pixmap in case the process hasnt finished so its better to run on a seperate thread and your problem will be solved.

Are you committed to that operational pipeline? Here's an alternate way to do the conversion you asked for:

  1. Implement com.badlogic.gdx.graphics.TextureData to take an android.graphics.Bitmap in the constructor.
  2. In prepare(), allocate and fill an IntBuffer using Bitmap.getPixels.
  3. Use bitmath to swap the data in the buffer from ARGB to RGBA: (arr[i] << 8) | (arr[i]>>24)
  4. In getType() return TextureData.TextureDataType.Compressed
  5. In consumeCompressedData() call glTexImage2D to feed the data into the (prebound) texture.

Your pipeline above includes several copies and recompressions of pixel data; this pipeline allows you to feed your Bitmap data straight into the texture with only one copy (necessary for the byte format conversion anyway). Would that work for you?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!