Alex Rivera | Logout

Java TGA loader

Asked 2009-10-03T15:24:09.973
9

I am looking for a small and free TGA (Targa) image loading class or library for Java. Ideally the result is a BufferedImage.

Yes, I have already googled, but most results are outdated, or are quite big libraries that contain a lot of other stuff I don't need. I am looking for something small and simple that reads just TGA images.

Edit
Report

1 Answer

3

Thanks for sharing it!

I've made some changes to improve performance. I'm only doing BGRA 32 Bits file decrypt, but it can help others people.

public static BufferedImage createTGAImage(byte[] buff) throws IOException {
    int offset = 0, width = 0, height = 0;
    int[] tgaBuffer = null;

    if (buff[2] == 0x02) { // BGRA File

        offset = 12;
        width = (buff[offset + 1] << 8 | buff[offset]);

        offset = 14;
        height = (buff[offset + 1] << 8 | buff[offset]);

        int colorDepth = buff[offset + 2];

        if (colorDepth == 0x20) { // 32 bits depth
            offset = 18;

            int count = width * height;
            tgaBuffer = new int[count];

            for (int i = 0; i < count; i++) {
                byte b = buff[offset++]; //This is for didatic prupose, you can remove it and make inline covert.
                byte g = buff[offset++];
                byte r = buff[offset++];
                byte a = buff[offset++];

                tgaBuffer[i] = ((a & 0xFF) << 24 | (r & 0xFF) << 16 | (g & 0xFF)<< 8 | b & 0xFF);
            }
        }
    }

    BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    result.setRGB(0, 0, width, height, tgaBuffer, 0, width);

    return result;
}
answered 2012-12-26T03:36:50.120

Your Answer