0

Can anybody help me? I am new to android and need to save a bitmap as a tga file.

And I also need to know how to load a tga file. I have tried using this (The android version) Java TGA loader but all I get is a solid white screen.

If anybody could suggest a library or way to do this please reply.

Thanks.

Community
  • 1
  • 1

1 Answers1

0

if android.graphics.Bitmap is what you're looking for, here it is:

 public static void writeTGA(Bitmap src, String path) throws IOException {

    ByteBuffer buffer = ByteBuffer.allocate(src.getRowBytes() * src.getHeight());
    src.copyPixelsToBuffer(buffer);
    boolean alpha = src.hasAlpha();
    byte[] data;

    byte[] pixels = buffer.array();
    if (pixels.length != src.getWidth() * src.getHeight() * (alpha ? 4 : 3))
        throw new IllegalStateException();

    data = new byte[pixels.length];

    for(int i=0;i < pixels.length; i += 4){// rgba -> bgra
        data[i] = pixels[i+2];
        data[i+1] = pixels[i+1];
        data[i+2] = pixels[i];
        data[i+3] = pixels[i+3];
    }

    byte[] header = new byte[18];
    header[2] = 2; // uncompressed, true-color image
    header[12] = (byte) ((src.getWidth() >> 0) & 0xFF);
    header[13] = (byte) ((src.getWidth() >> 8) & 0xFF);
    header[14] = (byte) ((src.getHeight() >> 0) & 0xFF);
    header[15] = (byte) ((src.getHeight() >> 8) & 0xFF);
    header[16] = (byte) (alpha ? 32 : 24); // bits per pixel
    header[17] = (byte) ((alpha ? 8 : 0) | (1 << 4));

    File file = new File(path);
    RandomAccessFile raf = new RandomAccessFile(file, "rw");
    raf.write(header);
    raf.write(data);
    raf.setLength(raf.getFilePointer()); // trim
    raf.close();
}
Stoica Mircea
  • 782
  • 10
  • 22