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.
What's the best way to convert an array of integers to the array of bytes in Java?
The byteValue() method of Integer class of java. lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte).
You can simply iterate the byte array and print the byte using System. out. println() method.
When an integer value is converted into a byte, Java cuts-off the left-most 24 bits. We will be using bitwise AND to mask all of the extraneous sign bits.
Yes you do. For bytes, you can only assign literals and constants between -128 and 127. Any other number, you need an explicit cast.
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, the order in which to write the bytes must be specified, 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]); } } }
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With