【问题标题】:Bitmap to Targa (TGA) save bug位图到 Targa (TGA) 保存错误
【发布时间】:2015-02-17 22:24:59
【问题描述】:

我目前正在使用以下代码将位图保存到 .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();
    }

预期的输出是这样的:

但结果是这样的:

我的猜测是我翻转了移位运算符之一。

【问题讨论】:

    标签: android tga


    【解决方案1】:
    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;
    

    【讨论】:

    • 想解释一下它是如何回答这个问题的?
    • @Mel 我猜他正在从 bgra 切换到 rgba。
    猜你喜欢
    • 1970-01-01
    • 2010-12-12
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 2010-10-13
    相关资源
    最近更新 更多