我正在使用 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.
这里,“位图的宽度”不是源的宽度,而是目标的宽度。 ArrayIndexOutOfBoundsException
在进行检查以确保提供的数组足够大以容纳请求的数据时,您会收到该异常。由于您的源位图比目标位图宽,因此数据所需的大小大于您传递的数组的大小。
垂直切片的调用应该是:
source.getPixels(verticalMiddleArray, 0, 1, width / 2, 0, 1, height);
(我假设你有 height - 1
作为尝试修复。)
关于java - 如何使用位图 getPixels 函数从列中复制像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47602308/