如何从原始图像中获取位图 [英] How to get a Bitmap from a raw image

查看:31
本文介绍了如何从原始图像中获取位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从网络读取原始图像.此图像是由图像传感器读取的,而不是从文件中读取的.

I am reading a raw image from the network. This image has been read by an image sensor, not from a file.

这些是我对图像的了解:
~ 高度 &宽度
~ 总大小(以字节为单位)
~ 8 位灰度
~ 1 字节/像素

These are the things I know about the image:
~ Height & Width
~ Total size (in bytes)
~ 8-bit grayscale
~ 1 byte/pixel

我正在尝试将此图像转换为位图以在图像视图中显示.

I'm trying to convert this image to a bitmap to display in an imageview.

这是我尝试过的:

BitmapFactory.Options opt = new BitmapFactory.Options();
opt.outHeight = shortHeight; //360
opt.outWidth = shortWidth;//248
imageBitmap = BitmapFactory.decodeByteArray(imageArray, 0, imageSize, opt);

decodeByteArray 返回 null,因为它无法解码我的图像.

decodeByteArray returns null, since it cannot decode my image.

我也尝试直接从输入流中读取它,而不是先将其转换为字节数组:

I also tried reading it directly from the input stream, without converting it to a Byte Array first:

imageBitmap = BitmapFactory.decodeStream(imageInputStream, null, opt);

这也返回null.

我已经搜索过这个 &其他论坛,但找不到实现此目的的方法.

I've searched on this & other forums, but cannot find a way to achieve this.

有什么想法吗?

我应该补充一点,我做的第一件事是检查流是否确实包含原始图像.我使用其他应用程序`(iPhone/Windows MFC)&他们能够阅读它并正确显示图像.我只需要想办法在 Java/Android 中做到这一点.

I should add that the first thing I did was to check if the stream actually contains the raw image. I did this using other applications `(iPhone/Windows MFC) & they are able to read it and display the image correctly. I just need to figure out a way to do this in Java/Android.

推荐答案

Android 不支持灰度位图.所以首先,您必须将每个字节扩展为 32 位 ARGB int.Alpha 为 0xff,R、G 和 B 字节是源图像字节像素值的副本.然后在该数组的顶部创建位图.

Android does not support grayscale bitmaps. So first thing, you have to extend every byte to a 32-bit ARGB int. Alpha is 0xff, and R, G and B bytes are copies of the source image's byte pixel value. Then create the bitmap on top of that array.

另外(见评论),似乎设备认为 0 是白色,1 是黑色 - 我们必须反转源位.

Also (see comments), it seems that the device thinks that 0 is white, 1 is black - we have to invert the source bits.

所以,让我们假设源图像位于名为 Src 的字节数组中.代码如下:

So, let's assume that the source image is in the byte array called Src. Here's the code:

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] = 0xff; // 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));

这篇关于如何从原始图像中获取位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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