Friday, January 11, 2013

Load image file as InputStream

This example demonstrate how to load image file as InputStream:

Load image file as InputStream
Load image file as InputStream


package javafxpixel;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
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 http://java-buddy.blogspot.com/
 */
public class JavaFXPixel extends Application {
    
    Label label;
    ImageView myImageView;
    
    @Override
    public void start(Stage primaryStage) {
        
        Button btnLoad = new Button("Load");
        btnLoad.setOnAction(btnLoadEventListener);
        
        label = new Label();
        myImageView = new ImageView();

        VBox rootBox = new VBox();
        rootBox.getChildren().addAll(btnLoad, label, myImageView);
        
        Scene scene = new Scene(rootBox, 300, 300);
        
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
    
    EventHandler<ActionEvent> btnLoadEventListener
    = new EventHandler<ActionEvent>(){

        @Override
        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);
            
            String path = file.getAbsolutePath();
            label.setText(path);
            
            try {
                InputStream inputStream = new FileInputStream(path);
                Image image = new Image(inputStream);
                myImageView.setImage(image);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(JavaFXPixel.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    };
}


Compare with Using ImageIO.read(file).

Next:
- Load a re-sized image


No comments:

Post a Comment