Java TGA loader

后端 未结 5 1421

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

Yes, I have already googled, but most results a

5条回答
  •  -上瘾入骨i
    2021-01-05 03:07

    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;
    }
    

提交回复
热议问题