How to Extract Colors From an Image in Java Netbeans
In this Java Tutorial we will see How To load an image and extract unique colors from it, and display those colors along with their codes using java netbeans.
What We Are Gonna Use In This Project:
- Java Programming Language.- NetBeans Editor.
Load Image Functionality:
The chooseAndDisplayImage() method is triggered when the "Load Image" button is clicked.
It uses JFileChooser to let the user select an image file.
If an image is selected, it's loaded using loadImage() and displayed in imageLabel.
Unique colors are then extracted and displayed using the extractUniqueColors() method.
Color Extraction:
The extractUniqueColors() method iterates through the image pixels, sampling every 10 pixels in both dimensions, and unique colors are stored in a HashSet.
Displaying Unique Colors:
The displayUniqueColors() method populates the colorsPanel with panels representing unique colors. Each color is displayed in a small square, and its corresponding code is shown below.
Components:
- JLabel (imageLabel): Displays the loaded image.
- JPanel (colorsPanel): Displays unique colors extracted from the image.
- JButton (loadImageButton): Initiates the process of loading an image.
- JFileChooser (fileChooser): Allows the user to choose an image file.
Project Source Code:
/**
*
* @author 1BestCsharp
*/
// Main class representing the application window
public class ColorsCodeExtractorApp extends JFrame{
// Label for displaying the loaded image
private final JLabel imageLabel;
// Panel for displaying unique colors
private final JPanel colorsPanel;
// Button for loading images
private JButton loadImageButton;
// Constructor for initializing the main application window
public ColorsCodeExtractorApp(){
// set up the frame
setTitle("Colors Code Extractor App");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800,700);
setLocationRelativeTo(null);
setLayout(new BorderLayout());
// Create a label for displaying the image
imageLabel = new JLabel();
imageLabel.setSize(getWidth(),getHeight());
imageLabel.setHorizontalAlignment(JLabel.CENTER);
imageLabel.setVerticalAlignment(JLabel.CENTER);
imageLabel.setOpaque(true);
imageLabel.setBackground(Color.WHITE);
// Create a panel for displaying unique colors
colorsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
colorsPanel.setBackground(Color.GRAY);
// Create a scrollable panel for the color display
JScrollPane colorsScrollPane = new JScrollPane(colorsPanel);
colorsScrollPane.setPreferredSize(new Dimension(colorsScrollPane.getPreferredSize().width, 100));
// Add components to the main frame
add(new JScrollPane(imageLabel), BorderLayout.CENTER);
add(colorsScrollPane, BorderLayout.SOUTH);
addLoadImageButton();
}
// Function to add the "Load Image" button
private void addLoadImageButton(){
loadImageButton = new JButton("Load Image");
loadImageButton.setPreferredSize(new Dimension(150,40));
loadImageButton.setFont(new Font("Arial",Font.BOLD,17));
loadImageButton.setBackground(new Color(30,144,255));
loadImageButton.setForeground(Color.WHITE);
loadImageButton.setBorderPainted(false);
loadImageButton.setFocusPainted(false);
loadImageButton.setContentAreaFilled(true);
loadImageButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
loadImageButton.addActionListener((e) -> {
// select and display image
chooseAndDisplayImage();
});
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.DARK_GRAY);
buttonPanel.add(loadImageButton);
add(buttonPanel, BorderLayout.NORTH);
}
// Function to handle choosing and displaying an image
private void chooseAndDisplayImage(){
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(this);
if(result == JFileChooser.APPROVE_OPTION){
// User selected a file
File selectedFile = fileChooser.getSelectedFile();
BufferedImage image = loadImage(selectedFile);
if(image != null){
// Display the selected image
imageLabel.setIcon(new ImageIcon(image));
extractUniqueColors(image);
}
else{
JOptionPane.showMessageDialog(this, "Failed to load the image");
}
}
}
// Function to load an image from a file
private BufferedImage loadImage(File file){
try{ return ImageIO.read(file); }
catch(IOException ex){
System.out.println(ex.getMessage());
return null;
}
}
// Function to display unique colors in the UI
private void displayUniqueColors(HashSet<Integer> uniqueColors){
// clear the panel
colorsPanel.removeAll();
// Create color panels and labels for each unique color
for(Integer rgb : uniqueColors){
Color color = new Color(rgb);
String colorCode = String.format("#%02X%02X%02X", color.getRed(), color.getGreen(),color.getBlue());
JPanel colorPanel = new JPanel();
colorPanel.setPreferredSize(new Dimension(60, 50));
colorPanel.setBackground(color);
JLabel colorLabel = new JLabel(colorCode);
colorLabel.setOpaque(true);
colorLabel.setBackground(Color.WHITE);
colorLabel.setHorizontalAlignment(JLabel.CENTER);
JPanel colorInfoPanel = new JPanel(new BorderLayout());
colorInfoPanel.add(colorPanel,BorderLayout.CENTER);
colorInfoPanel.add(colorLabel,BorderLayout.SOUTH);
colorsPanel.add(colorInfoPanel);
}
// Refresh the color display panel
colorsPanel.revalidate();
colorsPanel.repaint();
}
// Function to extract unique colors from the image
private void extractUniqueColors(BufferedImage image){
// Extract unique colors from the image
HashSet<Integer> uniqueColors = new HashSet<>();
int width = image.getWidth();
int height = image.getHeight();
for(int x = 0; x < width; x += 10){
for(int y = 0; y < height; y += 10){
int rgb = image.getRGB(x, y);
uniqueColors.add(rgb);
}
}
// Display the unique colors
displayUniqueColors(uniqueColors);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ColorsCodeExtractorApp app = new ColorsCodeExtractorApp();
app.setVisible(true);
}
}
The Final Result:
More Java Projects:
Download Projects Source Code