位图到Targa(TGA)保存错误

时间:2015-02-17 22:24:59

标签: android tga

我正在使用以下代码将Bitmap保存到.tga文件:

public static void writeTGA(Bitmap src, File file) 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, p = pixels.length - 1; i < data.length; i++, p--) {
            data[i] = pixels[p];
        }

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

        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        raf.write(header);
        raf.write(data);
        raf.setLength(raf.getFilePointer()); // trim
        raf.close();
    }

预期的输出是这样的: enter image description here

但结果如下:

enter image description here

我的猜测是我翻了一个位移操作符。

1 个答案:

答案 0 :(得分:0)

byte b = pixels[i];
byte g = pixels[i+1];
byte r = pixels[i+2];
byte a = pixels[i+3];
result[i]=r;
result[i+1]=g;
result[i+2]=b;
result[i+3]=a;