gpt4 book ai didi

Java TGA 加载器

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:00:17 27 4
gpt4 key购买 nike

我正在寻找用于 java 的小型免费 TGA 图像加载类或库。理想情况下,结果是 BufferedImage。

是的,我已经用谷歌搜索过,但大多数结果都已过时,或者是相当大的库,其中包含许多我不需要的其他内容。我正在寻找只读取 TGA 图像的小而简单的东西。

谢谢!

最佳答案

我有未压缩的 targa 图像,因此必须调整示例代码。这是我的编辑,它应该支持未压缩的 targa 24 位 BGR 和 32 位 BGRA

// http://paulbourke.net/dataformats/tga/
// little endian multi-byte integers: "low-order byte,high-order byte"
// 00,04 -> 04,00 -> 1024
class TargaReader {
public static BufferedImage getImage(String fileName) throws IOException {
File f = new File(fileName);
byte[] buf = new byte[(int)f.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
bis.read(buf);
bis.close();
return decode(buf);
}

private static int offset;

private static int btoi(byte b) {
int a = b;
return (a<0?256+a:a);
}

private static int read(byte[] buf) {
return btoi(buf[offset++]);
}

public static BufferedImage decode(byte[] buf) throws IOException {
offset = 0;

// Reading header bytes
// buf[2]=image type code 0x02=uncompressed BGR or BGRA
// buf[12]+[13]=width
// buf[14]+[15]=height
// buf[16]=image pixel size 0x20=32bit, 0x18=24bit
// buf{17]=Image Descriptor Byte=0x28 (00101000)=32bit/origin upperleft/non-interleaved
for (int i=0;i<12;i++)
read(buf);
int width = read(buf)+(read(buf)<<8); // 00,04=1024
int height = read(buf)+(read(buf)<<8); // 40,02=576
read(buf);
read(buf);

int n = width*height;
int[] pixels = new int[n];
int idx=0;

if (buf[2]==0x02 && buf[16]==0x20) { // uncompressed BGRA
while(n>0) {
int b = read(buf);
int g = read(buf);
int r = read(buf);
int a = read(buf);
int v = (a<<24) | (r<<16) | (g<<8) | b;
pixels[idx++] = v;
n-=1;
}
} else if (buf[2]==0x02 && buf[16]==0x18) { // uncompressed BGR
while(n>0) {
int b = read(buf);
int g = read(buf);
int r = read(buf);
int a = 255; // opaque pixel
int v = (a<<24) | (r<<16) | (g<<8) | b;
pixels[idx++] = v;
n-=1;
}
} else {
// RLE compressed
while (n>0) {
int nb = read(buf); // num of pixels
if ((nb&0x80)==0) { // 0x80=dec 128, bits 10000000
for (int i=0;i<=nb;i++) {
int b = read(buf);
int g = read(buf);
int r = read(buf);
pixels[idx++] = 0xff000000 | (r<<16) | (g<<8) | b;
}
} else {
nb &= 0x7f;
int b = read(buf);
int g = read(buf);
int r = read(buf);
int v = 0xff000000 | (r<<16) | (g<<8) | b;
for (int i=0;i<=nb;i++)
pixels[idx++] = v;
}
n-=nb+1;
}
}

BufferedImage bimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
bimg.setRGB(0, 0, width,height, pixels, 0,width);
return bimg;
}
}

关于Java TGA 加载器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1514035/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com