我必须为图像中的所有像素添加一些常量值-对于灰色图像和彩色图像。但是我不知道该怎么办。我通过BufferedImage读取图像,并且尝试获取2d像素数组。我发现类似BufferedImage.getRGB()的东西,但它返回奇怪的值(负值和巨大值)。如何为我的bufferedimage添加一些值?
您可以使用:
byte[] pixels = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();
要获得图像中所有像素的byte[]
,然后在byte[]
上循环,将常量添加到每个字节元素。
如果要将字节转换为二维字节[],我发现了一个仅执行该操作的示例(Get Two Dimensional Pixel Array)。
总的来说,代码如下:
private static int[][] convertToArrayLocation(BufferedImage inputImage) {
final byte[] pixels = ((DataBufferByte) inputImage.getRaster().getDataBuffer()).getData(); // get pixel value as single array from buffered Image
final int width = inputImage.getWidth(); //get image width value
final int height = inputImage.getHeight(); //get image height value
int[][] result = new int[height][width]; //Initialize the array with height and width
//this loop allocates pixels value to two dimensional array
for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel++) {
int argb = 0;
argb = (int) pixels[pixel];
if (argb < 0) { //if pixel value is negative, change to positive
argb += 256;
}
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
return result; //return the result as two dimensional array
} //!end of method!//
要向所有像素添加常数值,可以使用RescaleOp,您的常数将是每个通道的offset
。将scale
保留在[C0],并且1.0
可能是hints
。
null
要更改当前图像,而不是创建新图像,可以使用:
// Positive offset makes the image brighter, negative values makes it darker
int offset = 100; // ...or whatever your constant value is
BufferedImage brighter = new RescaleOp(1, offset, null)
.filter(image, null);