如何将 int[] 转换为 byte[] [英] How to convert int[] to byte[]

查看:35
本文介绍了如何将 int[] 转换为 byte[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an array of integers which represent a RGB image and would like to convert it to a byte array and save it to a file.

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

What's the best way to convert an array of integers to the array of bytes in Java?

推荐答案

正如 Brian 所说,你需要锻炼您需要什么样的转换.

As Brian says, you need to work out how what sort of conversion you need.

是否要将其另存为普通"图像文件(jpg、png 等)?

Do you want to save it as a "normal" image file (jpg, png etc)?

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

If so, you should probably use the Java Image I/O API.

如果你想以原始"格式保存它,必须指定写入字节的顺序,然后使用IntBuffer和NIO.

If you want to save it in a "raw" format, the order in which to write the bytes must be specified, and then use an IntBuffer and NIO.

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

As an example of using a ByteBuffer/IntBuffer combination:

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

这篇关于如何将 int[] 转换为 byte[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆