如何转换使用套接字接收的字节数组.
C++客户端发送uchar类型的图像数据.
在android端,我收到这个uchar数组作为byte [],范围从-128到+127.
我想要做的是接收这些数据并显示它.为此,我试图转换为Bitmap使用BitmapFactory.decodeByteArray(),但没有运气我得到null Bitmap.我做对了还是其他任何可用的方法.
提前致谢....
Alb*_*bin 10
From the comments to the answers above, it seems like you want to create a Bitmap object from a stream of RGB values, not from any image format like PNG or JPEG.
This probably means that you know the image size already. In this case, you could do something like this:
byte[] rgbData = ... // From your server
int nrOfPixels = rgbData.length / 3; // Three bytes per pixel.
int pixels[] = new int[nrOfPixels];
for(int i = 0; i < nrOfPixels; i++) {
int r = data[3*i];
int g = data[3*i + 1];
int b = data[3*i + 2];
pixels[i] = Color.rgb(r,g,b);
}
Bitmap bitmap = Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888);
Run Code Online (Sandbox Code Playgroud)
我在我的一个项目中一直在使用它,到目前为止,它已经非常可靠了.我不确定它是多么挑剔,尽管它没有被压缩为PNG.
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);
Run Code Online (Sandbox Code Playgroud)
编辑:我已经调整了这篇文章中的代码来使用RGB,所以下面的代码应该适合你.我还没有机会测试它,所以它可能需要一些调整.
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24600 次 |
| 最近记录: |