【问题标题】:How do I Save a bitmap as a tga file?如何将位图另存为 tga 文件?
【发布时间】:2014-10-18 00:57:51
【问题描述】:

有人可以帮我吗?我是 android 新手,需要将位图保存为 tga 文件。

而且我还需要知道如何加载 tga 文件。我试过用这个(安卓版)Java TGA loader 但我得到的只是一个纯白的屏幕。

如果有人可以建议图书馆或方法,请回复。

谢谢。

【问题讨论】:

    标签: android bitmap tga


    【解决方案1】:

    如果 android.graphics.Bitmap 是您正在寻找的,这里就是:

     public static void writeTGA(Bitmap src, String path) 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;i < pixels.length; i += 4){// rgba -> bgra
            data[i] = pixels[i+2];
            data[i+1] = pixels[i+1];
            data[i+2] = pixels[i];
            data[i+3] = pixels[i+3];
        }
    
        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));
    
        File file = new File(path);
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        raf.write(header);
        raf.write(data);
        raf.setLength(raf.getFilePointer()); // trim
        raf.close();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      相关资源
      最近更新 更多