如何将int []转换为byte []

妮可·加慕林(Niko Gamulin):

我有一个表示RGB图像的整数数组,想将其转换为字节数组并将其保存到文件中。

在Java中将整数数组转换为字节数组的最佳方法是什么?

乔恩·斯基特(Jon Skeet):

正如Brian所说,您需要弄清楚所需的转换方式。

您是否要将其另存为“正常”图像文件(jpg,png等)?

如果是这样,您可能应该使用Java Image I / O API。

如果要以“原始”格式保存,则必须指定写入字节的顺序,然后使用IntBuffer和NIO。

作为使用ByteBuffer / IntBuffer组合的示例:

import java.nio.*;
import java.net.*;

class Test
{   
    public static void main(String [] args)
        throws Exception // Just for simplicity!
    {
        int[] data = { 100, 200, 300, 400 };

        ByteBuffer byteBuffer = ByteBuffer.allocate(data.length * 4);        
        IntBuffer intBuffer = byteBuffer.asIntBuffer();
        intBuffer.put(data);

        byte[] array = byteBuffer.array();

        for (int i=0; i < array.length; i++)
        {
            System.out.println(i + ": " + array[i]);
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章