如何将位图保存为tga文件



有人能帮我吗?我是安卓系统的新手,需要将位图保存为tga文件。

我还需要知道如何加载tga文件。我已经尝试使用这个(android版本)Java TGA加载程序但我得到的只是一块纯白的屏幕。

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

谢谢。

如果您要查找的是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();
}

最新更新