Canvas.drawBitmap使用黄色色调绘制图像

时间:2012-06-26 02:36:37

标签: android bitmap camera

我试图通过onPreviewFrame从相机拍摄的图像中将'Y'组件绘制为灰度。

我正在使用Canvas.drawBitmap的版本,该版本将'colors'数组作为参数。 Android文档没有提到Color的格式,所以我假设ARGB 8888。

我确实显示了一个图像,但它显示出奇怪的黄色色调。

以下是我的代码:

  public void onPreviewFrame(byte[] bytes, Camera camera) {    
    Canvas canvas = null;
    try {
      synchronized(mSurfaceHolder) {
        canvas = mSurfaceHolder.lockCanvas();

        Size size = camera.getParameters().getPreviewSize();

        int width = size.width;
        int height = size.height;
        if (mHeight * mWidth != height * width)
        {
          mColors = new int[width * height];
          mHeight = height;
          mWidth = width;
          Log.i(TAG, "prewviw size = " + width + " x " + height);
        }
        for (int x = 0; x < width; x ++) {
          for (int y = 0; y < height; y++) {
            int yval = bytes[x + y * width];

            mColors[x + y * width] = (0xFF << 24) | (yval << 16) | (yval << 8) | yval;
          }
        }

        canvas.drawBitmap(mColors, 0, width, 0.f, 0.f, width, height, false, null);
      }
    }
    finally {
      if (canvas != null) {
        mSurfaceHolder.unlockCanvasAndPost(canvas);
      }
    }
  }

我还尝试使用另一个版本的Canvas.drawBitmap,它将Bitmap作为参数。我从同一个数组中以类似的方式构造了Bitmap,并告诉它明确使用ARGB。但它仍然最终被染成了黄色!

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

这是一种不同的方法,但以下工作方式,并且不会因解决方案的颜色问题而受到影响:

    YuvImage yuv = new YuvImage(data, previewFormat, size.width, size.height, null);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    yuv.compressToJpeg(new Rect(0, 0, size.width, size.height), 50, out);

    byte[] bytes = out.toByteArray();
    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    canvas.drawBitmap(bitmap, null, new Rect(0, 0, size.width, size.height), null);

注意:这可能需要为每个帧分配数据,而解决方案却没有。

相关问题