【问题标题】:Swing PixelGrabber - Sorting DataSwing PixelGrabber - 数据排序
【发布时间】:2014-07-16 23:05:34
【问题描述】:

我正在将图像颜色分类为二维颜色数组(行/列)。我已经实现了PixelGrabber,但我无法准确理解正在发生的事情,以及我可以用data 做什么来排序到二维数组。谢谢!

File file = fc.getSelectedFile();

try {
    BufferedImage img = ImageIO.read(file);
    PixelGrabber grabber = new PixelGrabber(img, 0, 0, -1, -1, false);
    if (grabber.grabPixels()) {
        int width = grabber.getWidth();
        int height = grabber.getHeight();
        int[][] imageColors = new int[width][height]; //I want to store colors in here
        int[] data = (int[]) grabber.getPixels();
     }
 } catch (Exception f) {
 }

【问题讨论】:

  • 有一个example in the JavaDocs 演示了如何从像素数据中提取颜色分量。您也可以将其与this example 混合使用
  • int alpha = (pixel >> 24) & 0xff;中的>>操作符有什么作用?
  • 从packed int中提取颜色分量,这里提取颜色的alpha分量
  • 我真的建议不要将PixelGrabberBufferedImage 一起使用。这真的只是做与img.getRGB(0, 0, w, h, null, 0, w) 相同的事情的一种非常缓慢的方式。 PixelGrabber 类旨在与旧的 ImageProducer/Consumer API 一起使用。

标签: java image swing image-processing


【解决方案1】:

PixelGrabber返回的像素数组基本上是像素数据的一维数组,基本上是图像数据的“平面”表示

要在给定的 x/y 位置获取特定像素,您需要将数组中的位置偏移(y * width) + x。因此,要将像素数据从一维数组复制到二维数组,您需要一个复合 for 循环。比如……

for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
        imageColors[x][y] = data[(y * width) + x];
    }
}

【讨论】:

  • 谢谢你,这真的很好用!一个简单的问题,在我们执行int alpha = (pixel&gt;&gt;24)... 之前,颜色存储的格式是什么?如果它有一个特定的名称,它将更容易以原始格式进行研究和使用。
  • 根据图像的类型,它被称为打包的 int 或打包的字节。您还可以使用 Color(int, boolean),将打包的 int 传递给 Color 类,并且 boolean 用于确定是否应该提取 alpha,但我个人觉得它更简单,因为我不需要记住逐位计算
猜你喜欢
  • 1970-01-01
  • 2011-11-02
  • 2015-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-26
  • 2012-08-12
  • 2017-06-19
相关资源
最近更新 更多