Java Loop through pixels in an image?
I'm trying to find a way to make maps for my 2D java game, and I thought of one Idea in which I would loop through each pixel of an image and depends on what color the pixel it was that would be the tile to draw.
e.g.
Is it possible to loop through an Images pixels? If it is, how?
Could you please supply me with some helpful开发者_高级运维 links or code snippets?
Note that if you want to loop over all pixels in an image, make sure to make the outer loop over the y-coordinate, like so:
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);
}
}
This will likely make your code much faster, as you'll be accessing the image data in the order it's stored in memory. (As rows of pixels.)
I think Pixelgrabber is what you looking for. If you have problems with the code please write a comment. Here is the link to the javadoc: [Pixelgrabber][1] and another short examples: [Get the color of a specific pixel][2], Java program to get the color of pixel
The following example is from the last link. Thanks to 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
精彩评论