Android字节数组转位图如何 [英] Android byte array to Bitmap How to

查看:16
本文介绍了Android字节数组转位图如何的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何转换使用套接字接收的字节数组.

How can I convert byte array received using socket.

  1. C++ 客户端发送 uchar 类型的图像数据.

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

在 android 端,我收到这个 uchar 数组作为 byte[],范围从 -128 到 +127.

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

我想做的是接收这些数据并显示出来.为此,我试图使用 BitmapFactory.decodeByteArray() 转换为 Bitmap,但不幸的是我得到了 null Bitmap.我做得对还是其他任何可用的方法.

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.

提前致谢....

推荐答案

我一直在我的一个项目中像下面这样使用它,到目前为止它非常可靠.我不确定它有多挑剔,因为它没有被压缩为 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);

我改编了这篇文章中的代码使用 RGB,所以下面的代码应该适合你.我还没有机会测试它,所以它可能需要一些调整.

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);

这篇关于Android字节数组转位图如何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆