【问题标题】:Java: Get the RGBA from a Buffered Image as an Array of IntegerJava:从缓冲图像中获取 RGBA 作为整数数组
【发布时间】:2023-03-28 02:15:02
【问题描述】:

给定一个图像文件,比如 PNG 格式,我如何获得一个 int [r,g,b,a] 数组,表示位于第 i 行第 j 列的像素?

到目前为止,我从这里开始:

private static int[][][] getPixels(BufferedImage image) {

    final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    final int width = image.getWidth();
    final int height = image.getHeight();

    int[][][] result = new int[height][width][4];

    // SOLUTION GOES HERE....
}

提前致谢!

【问题讨论】:

  • 从图像中获取像素数据作为int,将其传递给Color(int, boolean)
  • 您能否提供代码作为接受的答案?
  • “从图像中以 int 形式获取像素数据,将其传递给 Color(int, boolean)”:这是一堆废话
  • @gpasch 我认为您需要重新表述该评论,以使其礼貌和建设性的部分更加明显。否则它只会读作“近五年前提到的东西不再是最现代的解决方案”,并且可能被误认为是完全没有信息的东西,甚至可能是粗鲁的。

标签: java arrays pixel bufferedimage rgba


【解决方案1】:

您需要将打包的像素值作为int 获取,然后您可以使用Color(int, boolean) 构建一个颜色对象,您可以从中提取RGBA 值,例如...

private static int[][][] getPixels(BufferedImage image) {
    int[][][] result = new int[height][width][4];
    for (int x = 0; x < image.getWidth(); x++) {
        for (int y = 0; y < image.getHeight(); y++) {
            Color c = new Color(image.getRGB(i, j), true);
            result[y][x][0] = c.getRed();
            result[y][x][1] = c.getGreen();
            result[y][x][2] = c.getBlue();
            result[y][x][3] = c.getAlpha();
        }
    }
}

这不是最有效的方法,但它是最简单的方法之一

【讨论】:

  • result[y][x][3] = c.getAlpha();...?
【解决方案2】:

BufferedImages 有一个名为 getRGB(int x, int y) 的方法,它返回一个 int,其中每个字节都是像素的组成部分(alpha、红色、绿色和蓝色)。如果您不想自己执行按位运算符,您可以使用 Colors.getRed/Green/Blue 方法,方法是使用 getRGB 中的 int 创建 Java.awt.Color 的新实例。

您可以在循环中执行此操作以填充三维数组。

【讨论】:

    【解决方案3】:

    这是我解决这个问题的代码:

     File f = new File(filePath);//image path with image name like "lena.jpg"
     img = ImageIO.read(f);
    
     if (img==null) //if img null return
        return;
     //3d array [x][y][a,r,g,b]  
     int [][][]pixel3DArray= new int[img.getWidth()][img.getHeight()][4];
         for (int x = 0; x < img.getWidth(); x++) {
             for (int y = 0; y < img.getHeight(); y++) {
    
                int px = img.getRGB(x,y); //get pixel on x,y location
    
                //get alpha;
                pixel3DArray[x][y][0] =(px >> 24)& 0xff; //shift number and mask
    
                //get red
                pixel3DArray[x][y][1] =(px >> 16)& 0xff;
    
    
                //get green
                pixel3DArray[x][y][2] =(px >> 8)& 0xff;
    
                //get blue
                pixel3DArray[x][y][3] =(px >> 0)& 0xff;
    
             }
        }
    

    【讨论】:

      猜你喜欢
      • 2013-04-14
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      • 1970-01-01
      • 2011-09-25
      相关资源
      最近更新 更多