将 Java BufferedImage 发送到位图 Android

Send Java BufferedImage to Bitmap Android

您好,我正在尝试通过 tcp 套接字将 Java 应用程序中的 BufferedImage 发送到 Android 设备。我目前从 BufferedImage 中获取 byte[] 中的栅格,然后通过普通的 OutputStream 将其发送到设备。这工作正常,我在 Android 端得到相同的字节数组。但是,当我调用 Bitmap.decodeByteArray() 时,我只会得到 null。

这是我必须在 Java 中发送图片的代码。 BufferedImage 的图像类型是 TYPE_4BYTE_ABGR

byte[] imgBytes =    ((DataBufferByte)msg.getImage().getData().getDataBuffer()).getData();

lineBytes = (String.valueOf(imgBytes.length) + '\n').getBytes();        
out.write(lineBytes);
out.write(imgBytes);
out.write((int)'\n');
out.flush();

我写的第一件事是图像的大小,所以我知道 Android 上的 byte[] 有多大。

这是我试图用来创建 Android 位图的代码。

currLine = readLine(in);
int imgSize = Integer.parseInt(currLine);
byte[] imgBytes = new byte[imgSize];
in.read(imgBytes);
BitmapFactory.Options imgOptions = new BitmapFactory.Options();
imgOptions.inPreferredConfig = Bitmap.Config.ARGB_4444;

Bitmap img = BitmapFactory.decodeByteArray(imgBytes, 0, imgSize, imgOptions);

字节顺利到达。它们只是不适用于位图。

imgSize应该是图片的大小。为什么不试试 imgBytes.length

详细说明我在评论中提出的建议:

从 Java/server 端发送图像的宽度和高度(如果您知道图像的类型始终是 TYPE_4BYTE_ABGR,则不需要任何其他信息):

BufferedImage image = msg.getImage();
byte[] imgBytes = ((DataBufferByte) image.getData().getDataBuffer()).getData();

// Using DataOutputStream for simplicity
DataOutputStream data = new DataOutputStream(out);

data.writeInt(image.getWidth());
data.writeInt(image.getHeight());
data.write(imgBytes);

data.flush();

现在您可以在服务器端或客户端将交错的 ABGR 字节数组转换为 packed int ARGB,这并不重要。为简单起见,我将在 Android/client 端显示转换:

// Read image data
DataInputStream data = new DataInputStream(in);
int w = data.readInt();
int h = data.readInt();
byte[] imgBytes = new byte[w * h * 4]; // 4 byte ABGR
data.readFully(imgBytes);

// Convert 4 byte interleaved ABGR to int packed ARGB
int[] pixels = new int[w * h];
for (int i = 0; i < pixels.length; i++) {
    int byteIndex = i * 4;
    pixels[i] = 
            ((imgBytes[byteIndex    ] & 0xFF) << 24) 
          | ((imgBytes[byteIndex + 3] & 0xFF) << 16) 
          | ((imgBytes[byteIndex + 2] & 0xFF) <<  8) 
          |  (imgBytes[byteIndex + 1] & 0xFF);
} 

// Finally, create bitmap from packed int ARGB, using ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(pixels, w, h, Bitmap.Config.ARGB_8888);

如果你真的想要 ARGB_4444,你可以转换位图,但请注意,该常量在 Android API.

的所有最新版本中都已弃用