How to change the aspect ratio of an image in JavaFX?


The javafx.scene.image.Image class is used to load an image into a JavaFX application. This supports BMP, GIF, JPEG, and, PNG formats.

JavaFX provides a class named javafx.scene.image.ImageView is a node that is used to display, the loaded image.

The preserveRatio property of the ImageView class (boolean) specifies whether the aspect ratio of an image should be preserved, while displaying it using the current ImageView object. You can set the value to this property using the setPreserveRatio() method.

By default, the value of this property is true, i.e. though you change the width or height of the image, the aspect ratio of the displayed image will be the same as the source.

To change the aspect ratio of an image −

  • Instantiate the Image class by passing the URL (string) of the required image as a parameter.

  • Instantiate the ImageView class.

  • Set the image to it by passing above the image object as a parameter to the setImage() method.

  • Set the preserveRatio property to false using the setPreserveRatio() method.

  • Now, if you change the with or, the height of the image, its aspect ratio will be tampered.

Example

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class PerspectiveRatioExample extends Application {
   public void start(Stage stage) throws IOException {
      //creating the image object
      InputStream stream = new FileInputStream("D:\images\elephant.jpg");
      Image image = new Image(stream);
      //Creating the image view
      ImageView imageView1 = new ImageView(image);
      //Setting the image view parameters
      imageView1.setX(170);
      imageView1.setY(10);
      imageView1.setFitWidth(270);
      imageView1.setPreserveRatio(true);
      //Creating the image view
      ImageView imageView2 = new ImageView(image);
      //Setting the image view parameters
      imageView2.setX(10);
      imageView2.setY(180);
      imageView2.setFitWidth(580);
      imageView2.setFitHeight(160);
      imageView2.setPreserveRatio(false);
      //Setting the Scene object
      Group root = new Group(imageView1, imageView2);
      Scene scene = new Scene(root, 595, 350, Color.BEIGE);
      stage.setTitle("Perspective Ratio Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]) {
      launch(args);
   }
}

Output

Updated on: 16-May-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements