Android的字节数组为位图如何位图、数组、字节、Android

2023-09-07 10:19:35 作者:污仙

我如何可以转换使用套接字接收的字节数组。

How can I convert byte array received using socket.

这是UCHAR类型的C ++客户端发送的图像数据。

The C++ client send image data which is of type uchar.

在Android的一面,我收到此UCHAR数组作为字节[],这是范围从-128到+127。

At the android side I am receiving this uchar array as byte[] which is ranges from -128 to +127.

我想要做的是接收该数据并显示它。对于我试图转换使用 BitmapFactory.de codeByteArray()为位图,但没有运气我得到空的位图。我做正确的或可用任何其他方法。

What I wanted to do is that receives this data and display it. For that I was trying to convert to Bitmap using BitmapFactory.decodeByteArray(), but no luck I am getting null Bitmap. Am I doing right or any other method available.

在此先感谢....

推荐答案

我一直在使用它象下面这样在我的项目之一,到目前为止,它已经pretty的固体。我不知道它是多么挑剔,只要它不是COM pressed为PNG虽然。

I've been using it like below in one of my projects and so far it's been pretty solid. I'm not sure how picky it is as far as it not being compressed as a PNG though.

byte[] bytesImage;
Bitmap bmpOld;   // Contains original Bitmap
Bitmap bmpNew;

ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
bmpOld.compress(Bitmap.CompressFormat.PNG, 100, baoStream);
bytesImage = baoStream.toByteArray();
bmpNew = BitmapFactory.decodeByteArray(bytesImage, 0, bytesImage.length);

编辑:我已经适应从code this帖子使用RGB,所以下面的code应该为你工作。我还没有机会测试它却又如此,它可能需要一些调整。

edit: I've adapted the code from this post to use RGB, so the code below should work for you. I haven't had a chance to test it yet so it may need some adjusting.

Byte[] bytesImage = {0,1,2, 0,1,2, 0,1,2, 0,1,2};
int intByteCount = bytesImage.length;
int[] intColors = new int[intByteCount / 3];
int intWidth = 2;
int intHeight = 2;
final int intAlpha = 255;
if ((intByteCount / 3) != (intWidth * intHeight)) {
    throw new ArrayStoreException();
}
for (int intIndex = 0; intIndex < intByteCount - 2; intIndex = intIndex + 3) {
    intColors[intIndex / 3] = (intAlpha << 24) | (bytesImage[intIndex] << 16) | (bytesImage[intIndex + 1] << 8) | bytesImage[intIndex + 2];
}
Bitmap bmpImage = Bitmap.createBitmap(intColors, intWidth, intHeight, Bitmap.Config.ARGB_8888);
 
精彩推荐
图片推荐