简体   繁体   English

Java - 将 byte[] 转换为 int[] rgb

[英]Java - Convert byte[] to int[] rgb

I have an int array that i obtained by using RobotPeer.getRGBPixels().我有一个通过使用 RobotPeer.getRGBPixels() 获得的 int 数组。 I convert it to an byte array to send it over socket by using:我将其转换为字节数组,以使用以下方法通过套接字发送它:

 public static byte[] toByteArray(int[] ints){
    byte[] bytes = new byte[ints.length * 4];
            for (int i = 0; i < ints.length; i++) {
        bytes[i * 4] = (byte) (ints[i] & 0xFF);
        bytes[i * 4 + 1] = (byte) ((ints[i] & 0xFF00) >> 8);
        bytes[i * 4 + 2] = (byte) ((ints[i] & 0xFF0000) >> 16);
        bytes[i * 4 + 3] = (byte) ((ints[i] & 0xFF000000) >> 24);
    }
    return bytes;
}

Problem is: I use this method:问题是:我使用这种方法:

public static int[] toIntArray(byte buf[]) {
    int intArr[] = new int[buf.length / 4];
    int offset = 0;
    for (int i = 0; i < intArr.length; i++) {
        intArr[i] = (buf[3 + offset] & 0xFF) | ((buf[2 + offset] & 0xFF) << 8)
                | ((buf[1 + offset] & 0xFF) << 16) | ((buf[0 + offset] & 0xFF) << 24);
        offset += 4;
    }
    return intArr;
}

to get back int array.取回 int 数组。 Then i create BufferedImage from it and i get: https://www.dropbox.com/s/p754u3tnivigu70/test.jpeg然后我从它创建 BufferedImage 并得到: https : //www.dropbox.com/s/p754u3tnvigu70/test.jpeg

Please help me to solve that problem.请帮我解决这个问题。

Don't bother with bit shifting etc;不要打扰位移等; Java has ByteBuffer which can handle that for you, and endianness to boot: Java 有ByteBuffer可以为你处理它,以及启动的字节序:

public static int[] toIntArray(byte buf[]) 
{
    final ByteBuffer buffer = ByteBuffer.wrap(buf)
        .order(ByteOrder.LITTLE_ENDIAN);
    final int[] ret = new int[buf.length / 4];
    buffer.asIntBuffer().put(ret);
    return ret;
}

Similarly, the reverse:同样,反过来:

public static byte[] toByteArray(int[] ints)
{
    final ByteBuffer buf = ByteBuffer.allocate(ints.length * 4)
        .order(ByteOrder.LITTLE_ENDIAN);
    buf.asIntBuffer().put(ints);
    return buf.array();
}

Don't forget to specify endianness in your case since ByteBuffer s are big endian by default.不要忘记在您的情况下指定字节序,因为ByteBuffer s 默认情况下是大字节序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM