1

有谁能够帮我?我是 android 新手,需要将位图保存为 tga 文件。

而且我还需要知道如何加载 tga 文件。我尝试过使用这个(Android 版本)Java TGA 加载器 ,但我得到的只是一个纯白的屏幕。

如果有人可以建议一个图书馆或这样做的方法,请回复。

谢谢。

4

1 回答 1

0

如果 android.graphics.Bitmap 是您正在寻找的,这里是:

 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();
}
于 2017-05-17T21:07:35.353 回答