我正在从相机中检索一张原始图像,该图像的规格如下:
- 80 x 60 分辨率
- 4位灰度
我将图像作为字节数组检索,并拥有一个长度为2400 (1/2 * 80 * 60) 字节的数组。下一步是将字节数组转换为位图。我已经使用了
BitmapFactory.decodeByteArray(bytes, 0, bytes.length)
但是这并没有返回一个可显示的图片。我看了这篇文章,并将下面的代码复制到我的安卓应用程序中,但我得到了“缓冲区不足以容纳像素”的运行时错误。
byte [] Src; //Comes from somewhere...
byte [] Bits = new byte[Src.length*4]; //That's where the RGBA array goes.
int i;
for(i=0;i<Src.length;i++)
{
Bits[i*4] =
Bits[i*4+1] =
Bits[i*4+2] = ~Src[i]; //Invert the source bits
Bits[i*4+3] = -1;//0xff, that's the alpha.
}
//Now put these nice RGBA pixels into a Bitmap object
Bitmap bm = Bitmap.createBitmap(Width, Height, Bitmap.Config.ARGB_8888);
bm.copyPixelsFromBuffer(ByteBuffer.wrap(Bits));
在这个帖子的底部,原始的作者遇到了和我一样的错误。然而,他的问题已经通过上面粘贴的代码得到解决。有人能给我建议如何将原始图像或RGBA数组转换为位图吗?
非常感谢!
更新:
我按照Geobits的建议进行了修改,下面是我的新代码。
byte[] seperatedBytes = new byte[jpegBytes.length * 8];
for (int i = 0; i < jpegBytes.length; i++) {
seperatedBytes[i * 8] = seperatedBytes[i * 8 + 1] = seperatedBytes[i * 8 + 2] = (byte) ((jpegBytes[i] >> 4) & (byte) 0x0F);
seperatedBytes[i * 8 + 4] = seperatedBytes[i * 8 + 5] = seperatedBytes[i * 8 + 6] = (byte) (jpegBytes[i] & 0x0F);
seperatedBytes[i * 8 + 3] = seperatedBytes[i * 8 + 7] = -1; //0xFF
}
现在,我可以通过这个命令获取一个位图
Bitmap bm = BitmapFactory.decodeByteArray(seperatedBytes, 0, seperatedBytes.length);
但是位图大小为0KB。 我获取的图像是来自这个相机的原始图像。不幸的是,检索预压缩的JPEG图像不是一个选项,因为我需要4位灰度。
byte[] seperatedBytes = new byte[jpegBytes.length * 8]; for (int i = 0; i < jpegBytes.length; i++) { seperatedBytes[i * 8] = seperatedBytes[i * 8 + 1] = seperatedBytes[i * 8 + 2] = seperatedBytes[i * 8 + 3] = (byte) ((jpegBytes[i] >> 4) & (byte) 0x0F); seperatedBytes[i * 8 + 4] = seperatedBytes[i * 8 + 5] = seperatedBytes[i * 8 + 6] = seperatedBytes[i * 8 + 7] = (byte) (jpegBytes[i] & 0x0F); }
- Ankit Goyal`Bitmap bm = BitmapFactory.decodeByteArray(seperatedBytes, 0, seperatedBytes.length);`
我将 .jpg 文件保存到了 Android 上,但是它显示的文件大小为 0KB。数组 jpegBytes 的长度为 2400,而 seperatedBytes 数组的长度为 19200。 - Ankit GoyalRGBA_8888
,但应该是ARGB_8888
才能匹配格式。尝试交换每个像素的第一个/最后一个字节。不过这仍然不应该导致大小为0。你是如何保存图像的? - Geobits