java - 如何在Java中对像素进行算术运算
问题描述
我必须为图像中的所有像素添加一些恒定值 - 用于灰色图像和彩色图像。但我不知道我该怎么做。我通过 BufferedImage 读取图像,并试图获取二维像素数组。我发现了类似 BufferedImage.getRGB() 的东西,但它返回奇怪的值(负值和巨大值)。如何为我的缓冲图像添加一些价值?
解决方案
您可以使用:
byte[] pixels = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();
要获取byte[]
图像中的所有像素,然后循环byte[]
将常量添加到每个字节元素。
如果您希望将字节转换为二维字节 [],我找到了一个可以做到这一点的示例(获取二维像素数组)。
总之,代码如下所示:
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!//
推荐阅读
- reactjs - 尝试对数据进行排序时获取 _lodash2.default.orderBy 不是函数
- xslt - 将整个 xml 代码移动到另一个 xml 标记中
- php - Opencart Table Column Unable to Sort
- java - cannot be cast to java.lang.String
- amazon-web-services - 如何唯一标识一个 AWS Lambda 请求?
- php - 如何根据PHP中的子数组值对数组进行排序
- html - 滚动没有出现在移动视图中,因为内容尺寸很小
- python - Keras error - ValueError: could not convert string to float
- pdf - pdf hase 不显示填充 json 数据使用 jspdf
- javascript - 如何从 igcombo 获取所选项目的值