2009-07-06 24 views
48

Ho un array di interi che rappresentano un'immagine RGB e vorrebbero convertirlo in un array di byte e salvarlo in un file.Come convertire int [] a byte []

Qual è il modo migliore per convertire un array di interi alla matrice di byte in Java?

+0

Forse si otterrà risposte migliori e più appuntiti se si menziona motivi per cui si sceglie di convertire int [] a byte []. –

risposta

60

Come Brian dice, è necessario capire come che tipo di conversione è necessario.

Vuoi salvarlo come un file "normale" immagine (jpg, png ecc)?

Se è così, probabilmente si dovrebbe utilizzare l'API Java Image I/O.

Se si desidera salvarlo in un formato "raw", è necessario specificare l'ordine in cui scrivere i byte e quindi utilizzare uno IntBuffer e NIO.

Come esempio di utilizzare una combinazione 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]); 
     } 
    } 
} 
3

È necessario decidere di convertire 1 intero a una serie di byte prima.

Molto probabilmente (?) 1 intero a 4 byte e utilizzare gli operatori di spostamento (>> o <<) per estrarre ogni byte (osservare l'ordinamento dei byte!). Copia su un array di byte 4 volte la lunghezza dell'array intero.

8

Forse utilizzare questo metodo

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(); 
} 
+0

questo dividerà int a byte. non penso che questo sia ciò che è necessario. –

+0

vuole salvarlo in un file per utilizzarlo in un secondo momento, quindi questo sarebbe adatto – Ram

+0

Perché imposti 'baos' all'interno di' dos'? – Supuhstar

2

se il vostro intento è quello di salvare in un file che si desidera salvare forse direttamente in un file utilizzando FileOutputStream.write:

OutputStream os = new FileOutputStream("aa"); 
    int[] rgb = { 0xff, 0xff, 0xff }; 
    for (int c : rgb) { 
     os.write(c); 
    } 
    os.close(); 

poiché:

Scrive il byte specificato per questo flusso di output. Il contratto generale per la scrittura è che un byte viene scritto nel flusso di output. Il byte da scrivere è gli otto bit di basso ordine dell'argomento b. I 24 bit di ordine alto di b sono ignorati.

1

Ho creato questo codice e che sta funzionando piuttosto bene:

int IntToByte(byte arrayDst[], int arrayOrg[], int maxOrg){ 
     int i; 
     int idxDst; 
     int maxDst; 
     // 
     maxDst = maxOrg*4; 
     // 
     if (arrayDst==null) 
      return 0; 
     if (arrayOrg==null) 
      return 0; 
     if (arrayDst.length < maxDst) 
      return 0; 
     if (arrayOrg.length < maxOrg) 
      return 0; 
     // 
     idxDst = 0; 
     for (i=0; i<maxOrg; i++){ 
      // Copia o int, byte a byte. 
      arrayDst[idxDst] = (byte)(arrayOrg[i]); 
      idxDst++; 
      arrayDst[idxDst] = (byte)(arrayOrg[i] >> 8); 
      idxDst++; 
      arrayDst[idxDst] = (byte)(arrayOrg[i] >> 16); 
      idxDst++; 
      arrayDst[idxDst] = (byte)(arrayOrg[i] >> 24); 
      idxDst++; 
     } 
     // 
     return idxDst; 
    } 

    int ByteToInt(int arrayDst[], byte arrayOrg[], int maxOrg){ 
     int i; 
     int v; 
     int idxOrg; 
     int maxDst; 
     // 
     maxDst = maxOrg/4; 
     // 
     if (arrayDst==null) 
      return 0; 
     if (arrayOrg==null) 
      return 0; 
     if (arrayDst.length < maxDst) 
      return 0; 
     if (arrayOrg.length < maxOrg) 
      return 0; 
     // 
     idxOrg = 0; 
     for (i=0; i<maxDst; i++){ 
      arrayDst[i] = 0; 
      // 
      v = 0x000000FF & arrayOrg[idxOrg]; 
      arrayDst[i] = arrayDst[i] | v; 
      idxOrg++; 
      // 
      v = 0x000000FF & arrayOrg[idxOrg]; 
      arrayDst[i] = arrayDst[i] | (v << 8); 
      idxOrg++; 
      // 
      v = 0x000000FF & arrayOrg[idxOrg]; 
      arrayDst[i] = arrayDst[i] | (v << 16); 
      idxOrg++; 
      // 
      v = 0x000000FF & arrayOrg[idxOrg]; 
      arrayDst[i] = arrayDst[i] | (v << 24); 
      idxOrg++; 
     } 
     // 
     return maxDst; 
    } 
0

userei 'DataOutputStream' con 'ByteArrayOutputStream'.

public final class Converter { 

    private static final int BYTES_IN_INT = 4; 

    private Converter() {} 

    public static byte [] convert(int [] array) { 
     if (isEmpty(array)) { 
      return new byte[0]; 
     } 

     return writeInts(array); 
    } 

    public static int [] convert(byte [] array) { 
     if (isEmpty(array)) { 
      return new int[0]; 
     } 

     return readInts(array); 
    } 

    private static byte [] writeInts(int [] array) { 
     try { 
      ByteArrayOutputStream bos = new ByteArrayOutputStream(array.length * 4); 
      DataOutputStream dos = new DataOutputStream(bos); 
      for (int i = 0; i < array.length; i++) { 
       dos.writeInt(array[i]); 
      } 

      return bos.toByteArray(); 
     } catch (IOException e) { 
      throw new RuntimeException(e); 
     } 
    } 

    private static int [] readInts(byte [] array) { 
     try { 
      ByteArrayInputStream bis = new ByteArrayInputStream(array); 
      DataInputStream dataInputStream = new DataInputStream(bis); 
      int size = array.length/BYTES_IN_INT; 
      int[] res = new int[size]; 
      for (int i = 0; i < size; i++) { 
       res[i] = dataInputStream.readInt(); 
      } 
      return res; 
     } catch (IOException e) { 
      throw new RuntimeException(e); 
     } 
    } 
} 

    public class ConverterTest { 

    @Test 
    public void convert() { 
     final int [] array = {-1000000, 24000, -1, 40}; 
     byte [] bytes = Converter.convert(array); 
     int [] array2 = Converter.convert(bytes); 

     assertTrue(ArrayUtils.equals(array, array2)); 

     System.out.println(Arrays.toString(array)); 
     System.out.println(Arrays.toString(bytes)); 
     System.out.println(Arrays.toString(array2)); 
    } 
} 

Stampe:

[-1000000, 24000, -1, 40] 
[-1, -16, -67, -64, 0, 0, 93, -64, -1, -1, -1, -1, 0, 0, 0, 40] 
[-1000000, 24000, -1, 40] 
+2

Questo è quasi esattamente lo stesso di questa risposta: https://stackoverflow.com/a/1086071 (l'unica differenza che vedo è il tuo valore iniziale per 'ByteArrayOutputStream'). Puoi spiegare come questa risposta aggiunge nuove informazioni? – Tom

+0

Solo refactoring. –