您好,我正在尝试通过 TCP 套接字将 Java 应用程序上的 BufferedImage 发送到 Android 设备。我目前从 BufferedImage 获取字节 [] 中的栅格,然后通过普通的 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);
字节到达正常..它们只是不适用于位图。
最佳答案
详细说明我在评论中提出的建议:
从 Java/服务器端,发送图像的宽度和高度(如果您知道图像的类型始终为 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 字节数组转换为压缩 int ARGB,这并不重要。为了简单起见,我将在 Android/客户端显示转换:
// 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 中均已弃用。
关于java - 将 Java BufferedImage 发送到 Android 位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29453417/