Friday, December 21, 2012

JavaFX example: Copy image pixel-by-pixel using PixelReader and PixelWriter

javafx.scene.image.PixelReader and javafx.scene.image.PixelWriter defines methods for retrieving the pixel data from an Image or other surface containing pixels, and writing the pixel data of a WritableImage or other surface containing writable pixels.

Example to copy image pixel-by-pixel using PixelReader and PixelWriter.

Copy image pixel-by-pixel using PixelReader and PixelWriter
Copy image pixel-by-pixel using PixelReader and PixelWriter

package testjavafx;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

 * @web
public class TestJavaFX extends Application {
    public void start(Stage primaryStage) {
        Image image = new Image("");
        ImageView imageView = new ImageView();
        PixelReader pixelReader = image.getPixelReader();
        int width = (int)image.getWidth();
        int height = (int)image.getHeight();
        //Copy from source to destination pixel by pixel
        WritableImage writableImage 
                = new WritableImage(width, height);
        PixelWriter pixelWriter = writableImage.getPixelWriter();
        for (int y = 0; y < height; y++){
            for (int x = 0; x < width; x++){
                Color color = pixelReader.getColor(x, y);
                pixelWriter.setColor(x, y, color);
        ImageView destImageView = new ImageView();
        VBox vBox = new VBox();
        vBox.getChildren().addAll(imageView, destImageView);

        StackPane root = new StackPane();
        Scene scene = new Scene(root, 300, 300);

    public static void main(String[] args) {

No comments:

Post a Comment