【问题标题】:How to do arithmetic operations on pixels in Java如何在Java中对像素进行算术运算
【发布时间】:2020-04-28 23:04:33
【问题描述】:

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

【问题讨论】:

    标签: java pixel bufferedimage


    【解决方案1】:

    你可以使用:

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

    【讨论】:

    • 二维数组有什么办法吗?我有使用 int[][] 数组的要求。
    【解决方案2】:

    要为所有像素添加一个常数值,您可以使用RescaleOp。您的常数将是每个频道的offset。将scale 留给1.0hints 可能是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);
    

    要更改当前图像,而不是创建新图像,您可以使用:

    new RescaleOp(1, offset, null)
            .filter(image, image);
    

    【讨论】:

      猜你喜欢
      • 2013-02-27
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 1970-01-01
      • 2021-05-03
      • 2013-02-06
      相关资源
      最近更新 更多