如何从位图获取rgb值?

时间:2019-04-22 14:07:33

标签: java android bitmap rgb

我正在尝试通过以下代码从位图获取RGB。

我的最终目标是连续捕获屏幕并将其转换为抢劫。以下代码可以正常工作,但是非常慢。

有什么方法可以使其更快?

任何帮助将不胜感激。

//BTORGB
private byte[] rgbValuesFromBitmap(Bitmap bitmap)
{
    ColorMatrix colorMatrix = new ColorMatrix();
    ColorFilter colorFilter = new ColorMatrixColorFilter(colorMatrix);
    Bitmap argbBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
                                            Bitmap.Config.ARGB_4444);
    Canvas canvas = new Canvas(argbBitmap);
    Paint paint = new Paint();
    paint.setColorFilter(colorFilter);
    canvas.drawBitmap(bitmap, 0, 0, paint);

    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    int componentsPerPixel = 4;
    int totalPixels = width * height;
    int totalBytes = totalPixels * componentsPerPixel;

    byte[] rgbValues = new byte[totalBytes];
    @ColorInt int[] argbPixels = new int[totalPixels];
    bitmap.getPixels(argbPixels, 0, width, 0, 0, width, height);
    for (int i = 0; i < totalPixels; i++) {
        @ColorInt int argbPixel = argbPixels[i];
        int red = Color.red(argbPixel);
        int green = Color.green(argbPixel);
        int blue = Color.blue(argbPixel);
        int alpha = Color.alpha(argbPixel);

        rgbValues[i * componentsPerPixel + 0] = (byte) red;
        rgbValues[i * componentsPerPixel + 1] = (byte) green;
        rgbValues[i * componentsPerPixel + 2] = (byte) blue;
        //            rgbValues[i * componentsPerPixel + 3] = (byte) alpha;
    }

    return rgbValues;
}

0 个答案:

没有答案