7

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

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

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

这是我尝试过的:

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

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

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

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

这也返回null

我在这个论坛和其他论坛上搜索过,但找不到实现这一目标的方法。

有任何想法吗?

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

4

4 回答 4

14

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

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

因此,我们假设源图像位于名为 Src 的字节数组中。这是代码:

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));
于 2011-04-12T14:31:49.443 回答
1

一旦我做了这样的事情来解码从相机预览回调获得的字节流:

    Bitmap.createBitmap(imageBytes, previewWidth, previewHeight, 
                        Bitmap.Config.ARGB_8888);

试试看。

于 2011-04-11T20:32:32.407 回答
1
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.
}

转换循环将 8 位图像转换为 RGBA 可能需要很多时间,640x800 图像可能需要超过 500 毫秒...更快的解决方案是使用 ALPHA8 格式的位图并使用滤色器:

//setup color filter to inverse alpha, in my case it was needed
float[] mx = new float[]{
    1.0f, 0, 0, 0, 0, //red
    0, 1.0f, 0, 0, 0, //green
    0, 0, 1.0f, 0, 0, //blue
    0, 0, 0, -1.0f, 255 //alpha
};

ColorMatrixColorFilter cf = new ColorMatrixColorFilter(mx);
imageView.setColorFilter(cf);

// after set only the alpha channel of the image, it should be a lot faster without the conversion step

Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8);
bm.copyPixelsFromBuffer(ByteBuffer.wrap(src));  //src is not modified, it's just an 8bit grayscale array
imageview.setImageBitmap(bm);
于 2018-04-04T16:29:40.430 回答
0

使用 Drawable 从流创建。以下是使用 HttpResponse 的方法,但您可以随心所欲地获取输入流。

  InputStream stream = response.getEntity().getContent();

  Drawable drawable = Drawable.createFromStream(stream, "Get Full Image Task");
于 2011-04-11T20:47:35.553 回答