문제

RGB 이미지를 나타내는 정수 배열이 있으며 바이트 배열로 변환하여 파일로 저장하려고합니다.

정수 배열을 Java의 바이트 배열로 변환하는 가장 좋은 방법은 무엇입니까?

도움이 되었습니까?

해결책

처럼 브라이언 말하자면, 어떤 종류의 전환이 필요한지 알아 내야합니다.

"일반"이미지 파일 (JPG, PNG 등)으로 저장 하시겠습니까?

그렇다면 아마도 사용해야합니다 자바 이미지 I/O API.

"원시"형식으로 저장하려면 바이트를 작성하는 순서를 지정한 다음 사용해야합니다. IntBuffer 그리고 Nio.

바이트 버퍼/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]);
        }
    }
}

다른 팁

이 방법을 사용할 수도 있습니다

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

먼저 1 정수를 바이트 세트로 변환하는 방법을 결정해야합니다.

대부분 (?) 1 정수에서 4 바이트로, 시프트를 사용합니다 (>> 또는 <<) 연산자는 각 바이트를 꺼내려고합니다 (바이트 주문을보십시오!). 정수 배열의 길이의 4 배 바이트 배열로 복사하십시오.

파일에 저장하려는 의도가 있으면 fileoutputStream.write를 사용하여 파일에 직접 저장할 수 있습니다.

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

이후 :

이 출력 스트림에 지정된 바이트를 씁니다. 쓰기 계약은 하나의 바이트가 출력 스트림에 기록된다는 것입니다. 작성해야 할 바이트는 논증의 8 가지 저차 비트입니다. b. B의 24 개 고차 비트는 무시됩니다.

이 코드를 만들었고 잘 작동합니다.

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

'BytearRayoutputStream'과 함께 'dataOutputStream'을 사용합니다.

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

인쇄물:

[-1000000, 24000, -1, 40]
[-1, -16, -67, -64, 0, 0, 93, -64, -1, -1, -1, -1, 0, 0, 0, 40]
[-1000000, 24000, -1, 40]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top