Search code examples
javaimage-processingjavafxantialiasing

Disable ImageView Anti-Aliasing in JavaFX


I made an ImageView in JavaFX and load a pixel art into it. And I scaled up, but I can't clearly see the pixels of the art. The problem should be the anti-aliasing. So I need to see clearly the pixels like on the second link. How can I turn anti-aliasing off?

I tried with img1.setSmooth(false);

What I made in JavaFX: image1

How it supposed to look like: image2 //preview made in piskel

Here's my code:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application {
@Override public void start(Stage primaryStage) {
    AnchorPane root = new AnchorPane();
    StackPane hb = new StackPane();
    Image image = new Image("pixelart.png");
    ImageView img = new ImageView(image);
    img.setFitWidth(500);
    img.setFitHeight(500);
    img.setSmooth(false);
    hb.getChildren().add(img);
    root.getChildren().addAll(hb);
    Scene scene = new Scene(root,800,400);
    primaryStage.setScene(scene);
    primaryStage.show();    
}
public static void main(String[] args) {launch(args);}
}

pixelart.png: image3


Solution

  • One approach is to turn smoothing off when you construct the Image. Set the last argument of the constructor, smooth, to false.

    Image image = new Image("pixelart.png", 400, 400, true, false);
    

    image

    As tested:

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.image.Image;
    import javafx.scene.image.ImageView;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Stage;
    
    public class Main extends Application {
    
        @Override
        public void start(Stage primaryStage) {
            StackPane root = new StackPane();
            Image image = new Image("pixelart.png", 400, 400, true, false);
            ImageView view = new ImageView(image);
            root.getChildren().add(view);
            Scene scene = new Scene(root, 450, 450);
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }