Hi,
I have an array of integers which represent a RGB image and would like to convert it to the byte array and save it to the file.
Does anyone know what's the best way to convert an array of integers to the array of bytes in Java?
Thanks!
Hi,
I have an array of integers which represent a RGB image and would like to convert it to the byte array and save it to the file.
Does anyone know what's the best way to convert an array of integers to the array of bytes in Java?
Thanks!
You need to decide how you convert 1 integer to a set of bytes first.
Most probably (?) 1 integer to 4 bytes, and use the shift (>>
or <<
) operators to get each byte out (watch that byte ordering!). Copy to a byte array 4 times the length of the integer array.
Maybe use this method
byte[] integersToBytes(int[] values)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
for(int i=0; i < values.length; ++i)
{
dos.writeInt(values[i]);
}
return baos.toByteArray();
}
As Brian says, you need to work out how what sort of conversion you need.
Do you want to save it as a "normal" image file (jpg, png etc)? If so, you should probably use the Java Image I/O API.
If you want to save it in a "raw" format, you'll need to work out the order in which to write the bytes, and then use an IntBuffer
and NIO.
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]);
}
}
}
if your intent is to save to file you maybe want to save directly in a file using FileOutputStream.write:
OutputStream os = new FileOutputStream("aa");
int[] rgb = { 0xff, 0xff, 0xff };
for (int c : rgb) {
os.write(c);
}
os.close();
since it:
Writes the specified byte to this output stream. The general contract for write is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.