dermetfan

ImageToBitmapConverter

Feb 1st, 2014
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.68 KB | None | 0 0
  1. package net.dermetfan.someLibgdxTests;
  2.  
  3. import android.graphics.Bitmap;
  4. import android.graphics.Bitmap.Config;
  5.  
  6. import com.badlogic.gdx.graphics.Pixmap;
  7. import com.badlogic.gdx.graphics.Pixmap.Format;
  8. import com.badlogic.gdx.graphics.Texture;
  9. import com.badlogic.gdx.graphics.g2d.Batch;
  10. import com.badlogic.gdx.graphics.glutils.FrameBuffer;
  11. import com.badlogic.gdx.scenes.scene2d.ui.Image;
  12.  
  13. public class ImageToBitmapConverter {
  14.  
  15.     /** draws the given {@link Image} on a {@link FrameBuffer} and creates a {@link Bitmap} from the {@link FrameBuffer#getColorBufferTexture() texture}.
  16.      *  @param image the {@link Image} to draw
  17.      *  @param batch needed to draw the given {@link Image}
  18.      *  @return a {@link Bitmap} representation of the {@link Image} */
  19.     public static Bitmap convert(Image image, Batch batch) {
  20.         // draw on FBO
  21.         FrameBuffer fbo = new FrameBuffer(Format.RGBA8888, (int) image.getImageWidth(), (int) image.getImageHeight(), false);
  22.         fbo.begin();
  23.         batch.begin();
  24.         image.draw(batch, 1);
  25.         batch.end();
  26.         fbo.end();
  27.  
  28.         Texture texture = fbo.getColorBufferTexture();
  29.         fbo.dispose();
  30.  
  31.         // get a Pixmap from the texture
  32.         texture.getTextureData().prepare(); // consumePixmap() says "A call to prepare() must precede a call to this method."
  33.         Pixmap pixmap = texture.getTextureData().consumePixmap();
  34.         texture.dispose();
  35.  
  36.         // create a Bitmap from the pixmap
  37.         Bitmap bm = Bitmap.createBitmap((int) image.getImageWidth(), (int) image.getImageHeight(), Config.ARGB_8888); // maybe this will be an issue since libdgx's Format enum just provides RGBA_X formats and this is ARGB
  38.         bm.copyPixelsFromBuffer(pixmap.getPixels());
  39.         pixmap.dispose();
  40.  
  41.         return bm;
  42.     }
  43.  
  44. }
Advertisement
Add Comment
Please, Sign In to add comment