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

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

问题描述

我有重新present一个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?

推荐答案

说,你需要制定出你如何需要什么样的转换。

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图像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天全站免登陆