Thursday, June 30, 2016

92. Reading Pixel

A picture of President Obama was downloaded from whitehouse.org, and put in the src folder besides the ex92 folder. But of course this could be any image.


The Image object is used to get a PixelReader by using its getPixelReader() method. Using the PixelReader we can read a pixel, as we do in the handler for the mouse click.


The mouse click reads a color using the getArgb() method. This returns a 32 bit int. The first 8 bits are alpha, next 8 bits are red, next 8 bits are green, and last 8 bits are blue. All these four components are numbers from 0 to 255. For example to get Alpha we have to bit shift left 24 times (>> 24) and then logical and (&) with 255. The logical and serves to mask the first 24 bits so they will be zero. The three non-alpha color components are listed in label, and a Rectangle is filled with the color.


package ex92;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelReader;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class Ex92 extends Application {
    
    PixelReader pixelReader;
    int width, height;
    Label label;
    Rectangle rect;
    
    public static void main(String[] args) {
        Application.launch(args);
    }
    
    @Override
    public void start(Stage stage) {
        String imageFile = "president_official_portrait_lores.jpg";
        Image image = new Image(imageFile, 420, 524, false, true);
        ImageView imageView = new ImageView(image);
        imageView.setOnMouseClicked(this::handleClick);
        
        label = new Label("Click on picture");
        label.setFont(Font.font("Georgia", 24));
        
        rect = new Rectangle(420,100);
        rect.setFill(Color.WHITE);
        
        pixelReader = image.getPixelReader();
        width = (int)image.getWidth();
        height = (int)image.getHeight();
        
        VBox root = new VBox(50, imageView, label, rect);
        root.setPadding(new Insets(50));
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.setTitle("Example 92. Reading Pixel");
        stage.show();
    }
    
    private void handleClick(MouseEvent e) {
        int color = pixelReader.getArgb((int) e.getX(), (int) e.getY());
        int red = (color >> 16) & 0xff;
        int green = (color >> 8) & 0xff;
        int blue = color & 0xff;
        label.setText("Red: " + red + ", Green: " + green
                + ", Blue: " + blue);
        rect.setFill(Color.rgb(red, green, blue));
    }
}

This is the output when a reddish pixel (on the flag) was selected:


No comments:

Post a Comment