Reading the color value of an image is the basic logic of image recognition.
The code is as follows: |
Copy code |
Package com. javaer. image; Import java. awt. AWTException; Import java. awt. Dimension; Import java. awt. Rectangle; Import java. awt. Robot; Import java. awt. Toolkit; Import java. awt. image. BufferedImage; Import java. io. File; Import javax. imageio. ImageIO; Public class ReadColor { /** * Read the RGB value of an image. * @ Throws Exception */ Public void getImagePixel (String image) throws Exception { Int [] rgb = new int [3]; File file = new File (image ); BufferedImage bi = null; Try { Bi = ImageIO. read (file ); } Catch (Exception e ){ E. printStackTrace (); } Int width = bi. getWidth (); Int height = bi. getHeight (); Int minx = bi. getMinX (); Int miny = bi. getMinY (); System. out. println ("width =" + width + ", height =" + height + "."); System. out. println ("minx =" + minx + ", miniy =" + miny + "."); For (int I = minx; I <width; I ++ ){ For (int j = miny; j Int pixel = bi. getRGB (I, j); // the following three lines of code convert a number to an RGB number. Rgb [0] = (pixel & 0xff0000)> 16; Rgb [1] = (pixel & 0xff00)> 8; Rgb [2] = (pixel & 0xff ); System. out. println ("I =" + I + ", j =" + j + ":(" + rgb [0] + "," + rgb [1] + ", "+ rgb [2] + ")"); } } } /** * Return the screen color value. * * @ Param x * @ Param y * @ Return * @ Throws AWTException */ Public int getScreenPixel (int x, int y) throws AWTException {// The return value of the function is the RGB value of the color. Robot rb = null; // class in the java. awt. image package, which can be used to capture the screen, that is, screenshot. Rb = new Robot (); Toolkit tk = Toolkit. getDefaultToolkit (); // get the default Toolkit Dimension di = tk. getScreenSize (); // screen size System. out. println (di. width ); System. out. println (di. height ); Rectangle rec = new Rectangle (0, 0, di. width, di. height ); BufferedImage bi = rb. createScreenCapture (rec ); Int pixelColor = bi. getRGB (x, y ); Return 16777216 + pixelColor; // The value of pixelColor is negative. After practice, the maximum value of color is the actual color value. } /** * @ Param args */ Public static void main (String [] args) throws Exception { Int x = 0; ReadColor rc = new ReadColor (); X = rc. getScreenPixel (100,345 ); System. out. println (x + "-"); Rc. getImagePixel ("/a.jpg "); } } |