【问题标题】:Java Loop through pixels in an image?Java循环遍历图像中的像素?
【发布时间】:2011-12-06 16:27:52
【问题描述】:

我正在尝试寻找一种方法来为我的 2D Java 游戏制作地图,我想到了一个想法,我将循环遍历图像的每个像素,并取决于像素的颜色是什么瓷砖来绘制。

例如

是否可以循环遍历图像像素?如果是,如何?

能否请您提供一些有用的链接或代码 sn-ps?

【问题讨论】:

    标签: java image dictionary


    【解决方案1】:

    我认为 Pixelgrabber 正是您所寻找的。如果您对代码有问题,请写评论。这是 javadoc 的链接:[Pixelgrabber][1] 和另一个简短示例:[获取特定像素的颜色][2],Java program to get the color of pixel

    以下示例来自最后一个链接。感谢roseindia.net

    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    
    import javax.imageio.ImageIO;
    
    public class ImageTest
    {
        public static void main(final String args[])
            throws IOException
        {
            final File file = new File("c:\\example.bmp");
            final BufferedImage image = ImageIO.read(file);
    
            for (int x = 0; x < image.getWidth(); x++) {
                for (int y = 0; y < image.getHeight(); y++) {
                    final int clr = image.getRGB(x, y);
                    final int red = (clr & 0x00ff0000) >> 16;
                    final int green = (clr & 0x0000ff00) >> 8;
                    final int blue = clr & 0x000000ff;
    
                    // Color Red get cordinates
                    if (red == 255) {
                        System.out.println(String.format("Coordinate %d %d", x, y));
                    } else {
                        System.out.println("Red Color value = " + red);
                        System.out.println("Green Color value = " + green);
                        System.out.println("Blue Color value = " + blue);
                    }
                }
            }
        }
    }
    

    [1]:https://docs.oracle.com/javase/7/docs/api/java/awt/image/PixelGrabber.html [2]:http://www.rgagnon.com/javadetails/java-0257.html

    【讨论】:

    • 那么这个例子会得到每个像素吗?还是 100,400 处的像素?
    • 不,这个例子只是抓取像素 100;40,因为你需要循环遍历所有像素。我认为通过 image.width 和 image.height 的双循环应该可以解决您的问题。
    • PixelGrabber 链接已损坏
    • @Asaph 链接已修复
    • @TobiasSarnow 谢谢!
    【解决方案2】:

    请注意,如果您想遍历图像中的所有像素,请确保在 y 坐标上进行外部循环,如下所示:

    for (int y = 0; y < image.getHeight(); y++) {
        for (int x = 0; x < image.getWidth(); x++) {
              int  clr   = image.getRGB(x, y); 
              int  red   = (clr & 0x00ff0000) >> 16;
              int  green = (clr & 0x0000ff00) >> 8;
              int  blue  =  clr & 0x000000ff;
              image.setRGB(x, y, clr);
        }
    }
    

    这可能会使您的代码更快,因为您将按照图像数据在内存中的存储顺序访问图像数据。 (作为像素行。)

    【讨论】:

    • 这个答案使用什么图像类?
    • BufferedImage IIRC。 :)
    猜你喜欢
    • 2013-07-16
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 2015-05-09
    • 2011-10-05
    • 2015-01-15
    • 2012-07-25
    相关资源
    最近更新 更多