Search code examples
javaimagejavafxscale

JavaFX create a new image from an existing one


In JavaFX u can create a new Image from a string(path), how would i go about creating a new Image from an existing javafx.scene.image.image?

as following:

Image image2 = new Image("my/res/flower.png", 100, 150, false, false);

But instead of the path an actual image object.

I want to change the size of the image.


Solution

  • There is typically no need to create a new Image instance in order to perform rescaling. The API allows you to view or draw scaled versions of an existing Image instance. For example, given

    Image image = new Image("my/res/flower.png");
    

    you can create an ImageView that displays a scaled version with

    ImageView imageView = new ImageView(image);
    imageView.setFitWidth(100);
    imageView.setFitHeight(150);
    

    or you can draw a scaled version to a canvas with

    Canvas canvas = ... ;
    GraphicsContext gc = canvas.getGraphicsContext2D();
    gc.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), 0, 0, 100, 150);