如何使用位图 getPixels 函数从列中复制像素

How to copy pixels from a column using Bitmap getPixels function

我使用 Bitmap.getPixels 和下面的代码在位图图像中间获得一行 1 像素高度:

int width = source.getWidth();
int height = source.getHeight();
int[] horizontalMiddleArray = new int[width];

source.getPixels(horizontalMiddleArray, 0, width, 0, height / 2, width, 1);

结果类似于:

现在我想做同样的事情,但是在垂直方向:

我尝试了相同的逻辑,但它不起作用,我也看不出我做错了什么:

int[] verticalMiddleArray = new int[height];
source.getPixels(verticalMiddleArray, 0, width, width / 2, 0, 1, height -1 );

使用此代码我收到 ArrayIndexOutOfBoundsException 异常。

目前位图的大小是 32x32。

该方法的文档要么完全错误,要么无意误导,具体取决于解释。对于 stride 参数,它表示:

stride int: The number of entries in pixels[] to skip between rows (must be >= bitmap's width). Can be negative.

这里,"bitmap's width"不是源的宽度,而是目的地的宽度。当它进行检查以确保提供的数组足够大以容纳请求的数据时,您会得到 ArrayIndexOutOfBoundsException 。由于您的源位图比目标位图宽,因此数据所需的大小大于您传递的数组的大小。

垂直切片的调用应该是:

source.getPixels(verticalMiddleArray, 0, 1, width / 2, 0, 1, height);

(我假设您在那里尝试了 height - 1 修复。)