Thursday, January 17, 2013

Get width and height of javafx.scene.image.Image

To get width and height of javafx.scene.image.Image, simple call its getWidth() and getHeight() methods.

Get width and height of javafx.scene.image.Image
Get width and height of javafx.scene.image.Image

package javafxpixel;

import java.awt.image.BufferedImage;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.imageio.ImageIO;

 * @web
public class JavaFXPixel extends Application {
    Label label;
    ImageView myImageView;
    public void start(Stage primaryStage) {
        Button btnLoad = new Button("Load");
        label = new Label();
        myImageView = new ImageView();
        VBox rootBox = new VBox();
        rootBox.getChildren().addAll(btnLoad, label, myImageView);
        Scene scene = new Scene(rootBox, 300, 300);

    public static void main(String[] args) {
    EventHandler<ActionEvent> btnLoadEventListener
    = new EventHandler<ActionEvent>(){
        public void handle(ActionEvent t) {
            FileChooser fileChooser = new FileChooser();
            //Set extension filter
            FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
            FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
            fileChooser.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);
            //Show open file dialog
            File file = fileChooser.showOpenDialog(null);

            BufferedImage bufferedImage;
            try {
                bufferedImage =;
                Image image = SwingFXUtils.toFXImage(bufferedImage, null);
                label.setText("width: " + (int)image.getWidth()
                        + " x height: " + (int)image.getHeight());
            } catch (IOException ex) {
                Logger.getLogger(JavaFXPixel.class.getName()).log(Level.SEVERE, null, ex);


- bind widthProperty and heightProperty of Image
- Get width and height of resized imageView

No comments:

Post a Comment