Java program to get the color of pixel

In this java example program we have to write code for getting the pixel color of an image.

Java program to get the color of pixel

In this java example program we have to write code for getting the pixel color of an image.

Java program to get the color of pixel

Java program to get the color of pixel

     

In this java example program we have to write code for getting the pixel color of an image. To get the pixel color we need to first have an image and then we will be able to get the pixel color of any specific or particular pixel in the RGB format.

File file= new File("rockface.jpg");
BufferedImage image = ImageIO.read(file);

Above line of code creates an object of File with the image named "rockface.jpg" now we will read this file with the static method of ImageIO read(). Now we can get the pixel color with the getRGB() method with the image object.

Here is the example code of GetPixelColor.java as follows:

 

 

GetPixelColor.java

import java.io.*;
import java.awt.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

public class GetPixelColor
{
  public static void main(String args[]) throws IOException{
  File file= new File("rockface.jpg");
  BufferedImage image = ImageIO.read(file);
  // Getting pixel color by position x=100 and y=40 
  int clr=  image.getRGB(100,40)
  int  red   = (clr & 0x00ff0000>> 16;
  int  green = (clr & 0x0000ff00>> 8;
  int  blue  =  clr & 0x000000ff;
  System.out.println("Red Color value = "+ red);
  System.out.println("Green Color value = "+ green);
  System.out.println("Blue Color value = "+ blue);
  }
}

 

Output of the above Code:

C:\javaexamples>javac GetPixelColor.java

C:\javaexamples>java GetPixelColor
Red Color value = 33
Green Color value = 50
Blue Color value = 60

 

Download Source Code