java - 如何在Java中对像素进行算术运算

标签 java pixel bufferedimage

我必须为图像中的所有像素添加一些常量值 - 对于灰色图像和彩色图像。但我不知道该怎么做。我通过 BufferedImage 读取图像,并且尝试获取二维像素数组。 我发现类似 BufferedImage.getRGB() 的东西,但它返回奇怪的值(负值和巨大的值)。如何为我的缓冲图像添加一些值?

最佳答案

您可以使用:

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!//

关于java - 如何在Java中对像素进行算术运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61491439/

相关文章:

java - 将 Image 对象转换为 BufferedImage 对象

java - StaticUserAuthenticator 未在 VFS2 中设置 FTP 用户名

java - 我应该使用什么分辨率的图像?

java - 在 map 中,按一个字段排序并按另一个字段删除元素?

java - 在 Linux (Mageia) 上的 NetBeans 中从 Java 应用程序连接到 MariaDB

css - 在同一规则中混合百分比和像素是否存在问题?

图像识别

JAVA:为什么图像加载速度比应用程序、Window Frame 慢?

Java 屏幕截图(使用 Robot 和 BufferedImage.getRGB)

C#、C++ - 不安全的像素颜色查找器循环