Example to 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 http://java-buddy.blogspot.com/
*/
public class TestJavaFX extends Application {
@Override
public void start(Stage primaryStage) {
Image image = new Image("http://goo.gl/kYEQl");
ImageView imageView = new ImageView();
imageView.setImage(image);
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();
destImageView.setImage(writableImage);
VBox vBox = new VBox();
vBox.getChildren().addAll(imageView, destImageView);
StackPane root = new StackPane();
root.getChildren().add(vBox);
Scene scene = new Scene(root, 300, 300);
primaryStage.setTitle("java-buddy.blogspot.com");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}