Example usage for javafx.embed.swing SwingFXUtils fromFXImage

List of usage examples for javafx.embed.swing SwingFXUtils fromFXImage

Introduction

In this page you can find the example usage for javafx.embed.swing SwingFXUtils fromFXImage.

Prototype

public static BufferedImage fromFXImage(Image img, BufferedImage bimg) 

Source Link

Document

Snapshots the specified JavaFX Image object and stores a copy of its pixels into a BufferedImage object, creating a new object if needed.

Usage

From source file:org.sleuthkit.autopsy.imageanalyzer.ThumbnailCache.java

/**
 * save the generated thumbnail to disk in the cache folder with
 * the obj_id as the name.// w  ww . j  a va 2s.  com
 *
 * @param file the file the given image is a thumbnail for
 * @param bi   the thumbnail to save for the given DrawableFile
 */
private void saveIcon(final DrawableFile<?> file, final Image bi) {
    try {
        if (bi != null) {
            File f = getCacheFile(file.getId());
            //convert back to swing to save
            ImageIO.write(SwingFXUtils.fromFXImage(bi, null), FORMAT, f);
        }
    } catch (IllegalArgumentException | IOException ex) {
        LOGGER.log(Level.WARNING, "failed to save generated icon ", ex);
    }
}

From source file:org.sleuthkit.autopsy.imagegallery.ThumbnailCache.java

/**
 * save the generated thumbnail to disk in the cache folder with
 * the obj_id as the name.//from w ww  .  java 2s.  com
 *
 * @param file the file the given image is a thumbnail for
 * @param bi   the thumbnail to save for the given DrawableFile
 */
private void saveIcon(final DrawableFile<?> file, final Image bi) {
    try {
        if (bi != null) {
            File f = getCacheFile(file.getId());
            //convert back to swing to save
            ImageIO.write(SwingFXUtils.fromFXImage(bi, null), FORMAT, f);
        }
    } catch (IllegalArgumentException | IOException ex) {
        //LOGGER.log(Level.WARNING, "failed to save generated icon ", ex);
        LOGGER.log(Level.WARNING, "failed to save generated icon");
    }
}

From source file:org.sleuthkit.autopsy.coreutils.ImageUtils.java

/**
 * Get a thumbnail of a specified size for the given image. Generates the
 * thumbnail if it is not already cached.
 *
 * @param content  the content to generate a thumbnail for
 * @param iconSize the size (one side of a square) in pixels to generate
 *
 * @return a thumbnail for the given image or a default one if there was a
 *         problem making a thumbnail./*from w  w  w . ja va 2  s. c om*/
 */
public static BufferedImage getThumbnail(Content content, int iconSize) {
    if (content instanceof AbstractFile) {
        AbstractFile file = (AbstractFile) content;

        Task<javafx.scene.image.Image> thumbnailTask = newGetThumbnailTask(file, iconSize, true);
        thumbnailTask.run();
        try {
            return SwingFXUtils.fromFXImage(thumbnailTask.get(), null);
        } catch (InterruptedException | ExecutionException ex) {
            LOGGER.log(Level.WARNING, "Failed to get thumbnail for {0}: " + ex.toString(),
                    getContentPathSafe(content)); //NON-NLS
            return DEFAULT_THUMBNAIL;
        }
    } else {
        return DEFAULT_THUMBNAIL;
    }
}

From source file:eu.mihosoft.vrl.fxscad.MainController.java

@FXML
private void onExportAsPngFile(ActionEvent e) {

    if (csgObject == null) {
        Action response = Dialogs.create().title("Error").message("Cannot export PNG. There is no geometry :(")
                .lightweight().showError();

        return;/* ww w.ja  v  a  2s .c  om*/
    }

    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Export PNG File");
    fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image files (*.png)", "*.png"));

    File f = fileChooser.showSaveDialog(null);

    if (f == null) {
        return;
    }

    String fName = f.getAbsolutePath();

    if (!fName.toLowerCase().endsWith(".png")) {
        fName += ".png";
    }

    int snWidth = 1024;
    int snHeight = 1024;

    double realWidth = viewGroup.getBoundsInLocal().getWidth();
    double realHeight = viewGroup.getBoundsInLocal().getHeight();

    double scaleX = snWidth / realWidth;
    double scaleY = snHeight / realHeight;

    double scale = Math.min(scaleX, scaleY);

    PerspectiveCamera snCam = new PerspectiveCamera(false);
    snCam.setTranslateZ(-200);

    SnapshotParameters snapshotParameters = new SnapshotParameters();
    snapshotParameters.setTransform(new Scale(scale, scale));
    snapshotParameters.setCamera(snCam);
    snapshotParameters.setDepthBuffer(true);
    snapshotParameters.setFill(Color.TRANSPARENT);

    WritableImage snapshot = new WritableImage(snWidth, (int) (realHeight * scale));

    viewGroup.snapshot(snapshotParameters, snapshot);

    try {
        ImageIO.write(SwingFXUtils.fromFXImage(snapshot, null), "png", new File(fName));
    } catch (IOException ex) {
        Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:tachyon.java.manager.JavaFxManager.java

private String getIconPath() {
    if (getProject().getFileIconPath().isEmpty()) {
        return null;
    }/* ww  w  .j a va 2s. c o m*/
    if (OS.contains("win")) {
        if (getProject().getFileIconPath().endsWith(".ico")) {
            return getProject().getFileIconPath();
        } else {
            File f = new File(getProject().getFileIconPath());
            if (f.exists()) {
                File to = new File(getProject().getDist().toAbsolutePath().toString() + File.separator
                        + getFilename(f) + ".ico");
                if (!to.exists()) {
                    try {
                        Image im = new Image(f.toURI().toString(), 256, 256, true, true);
                        ICOEncoder.write(SwingFXUtils.fromFXImage(im, null), to);
                        if (to.exists()) {
                            return to.getAbsolutePath();
                        }
                    } catch (IOException ex) {
                    }
                } else {
                    return to.getAbsolutePath();
                }
            }
        }
    } else if (getProject().getFileIconPath().endsWith(".icns")) {
        return getProject().getFileIconPath();
    } else {
        File f = new File(getProject().getFileIconPath());
        if (f.exists()) {
            File to = new File(getProject().getDist().toAbsolutePath().toString() + File.separator
                    + getFilename(f) + ".icns");
            if (!to.exists()) {
                try {
                    Image im = new Image(f.toURI().toString());
                    Imaging.writeImage(SwingFXUtils.fromFXImage(im, null), f, null, null);
                    return to.getAbsolutePath();
                } catch (IOException | ImageWriteException ex) {
                }
            } else {
                return to.getAbsolutePath();
            }
        }
    }
    return null;
}

From source file:de.ifsr.adam.ImageGenerator.java

/**
 * Takes a snapshot of the Pane and prints it to a pdf.
 *
 * @return True if no IOException occurred
 *///from   w  w  w . j av a2s.  c  om
private boolean printToPDF(String filePath, Pane pane) {
    //Scene set up
    Group root = new Group();
    Scene printScene = new Scene(root);
    printScene.getStylesheets().add(this.stylesheetURI.toString());

    //Snapshot generation
    ArrayList<WritableImage> images = new ArrayList<>();
    try {
        ObservableList<Node> panes = pane.getChildren();
        for (int i = 0; i < panes.size(); i++) {
            GridPane gridPane = (GridPane) panes.get(i);
            ((Group) printScene.getRoot()).getChildren().clear();
            ((Group) printScene.getRoot()).getChildren().addAll(gridPane);
            images.add(printScene.snapshot(null));
            panes.add(i, gridPane);
        }
    } catch (Exception e) {
        log.error(e);
        return false;
    }

    //PDF Setup
    File outFile = new File(filePath + "." + "pdf");
    Iterator<WritableImage> iterImages = images.iterator();
    PDDocument doc = new PDDocument();

    try {

        while (iterImages.hasNext()) {
            //Page setup
            PDPage page = new PDPage();
            doc.addPage(page);
            PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, false);
            //Image setup
            BufferedImage bufImage = SwingFXUtils.fromFXImage(iterImages.next(), null);
            PDPixelMap pixelMap = new PDPixelMap(doc, bufImage);

            int width = (int) (page.getMediaBox().getWidth());
            int height = (int) (page.getMediaBox().getHeight());
            Dimension dim = new Dimension(width, height);
            contentStream.drawXObject(pixelMap, 0, 0, dim.width, dim.height);
            contentStream.close();
        }

        doc.save(outFile);
        return true;
    } catch (IOException | COSVisitorException e) {
        log.error(e);
        return false;
    }
}

From source file:de.ifsr.adam.ImageGenerator.java

/**
 * Takes a snapshot of the Pane and prints it to a file.
 *
 * @return True if no IOException occurred
 *///from   w w  w  . j a v a  2s .c o m
private boolean printToFile(String fileName, Pane pane) {
    Group root = new Group();
    Scene printScene = new Scene(root);

    printScene.getStylesheets().add(this.stylesheetURI.toString());

    ((Group) printScene.getRoot()).getChildren().addAll(pane);
    WritableImage image = printScene.snapshot(null);
    File outFile = new File(fileName + "." + formatName);

    try {
        ImageIO.write(SwingFXUtils.fromFXImage(image, null), formatName, outFile);
        return true;
    } catch (IOException e) {
        log.error(e);
        return false;
    }
}

From source file:be.makercafe.apps.makerbench.editors.JFXMillEditor.java

private void handleExportAsPngFile(ActionEvent e) {

    if (millObject == null) {
        Alert alert = new Alert(AlertType.ERROR);
        alert.setTitle("Oeps an error occured");
        alert.setHeaderText("Cannot export PNG. There is no geometry !");
        alert.setContentText("Please verify that your code generates a valid CSG object.");
        alert.showAndWait();/*from w  ww  .  jav  a 2s  . c o m*/
        return;
    }

    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Export PNG File");
    fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image files (*.png)", "*.png"));

    File f = fileChooser.showSaveDialog(null);

    if (f == null) {
        return;
    }

    String fName = f.getAbsolutePath();

    if (!fName.toLowerCase().endsWith(".png")) {
        fName += ".png";
    }

    int snWidth = 1024;
    int snHeight = 1024;

    double realWidth = viewGroup.getBoundsInLocal().getWidth();
    double realHeight = viewGroup.getBoundsInLocal().getHeight();

    double scaleX = snWidth / realWidth;
    double scaleY = snHeight / realHeight;

    double scale = Math.min(scaleX, scaleY);

    PerspectiveCamera snCam = new PerspectiveCamera(false);
    snCam.setTranslateZ(-200);

    SnapshotParameters snapshotParameters = new SnapshotParameters();
    snapshotParameters.setTransform(new Scale(scale, scale));
    snapshotParameters.setCamera(snCam);
    snapshotParameters.setDepthBuffer(true);
    snapshotParameters.setFill(Color.TRANSPARENT);

    WritableImage snapshot = new WritableImage(snWidth, (int) (realHeight * scale));

    viewGroup.snapshot(snapshotParameters, snapshot);

    try {
        ImageIO.write(SwingFXUtils.fromFXImage(snapshot, null), "png", new File(fName));
    } catch (IOException ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
        Alert alert = new Alert(AlertType.ERROR);
        alert.setTitle("Oeps an error occured");
        alert.setHeaderText("Cannot export PNG. There went something wrong writing the file.");
        alert.setContentText(
                "Please verify that your file is not read only, is not locked by other user or program, you have enough diskspace.");
        alert.showAndWait();
    }
}

From source file:net.rptools.tokentool.controller.ManageOverlays_Controller.java

@FXML
void overlayViewFlowPane_DragDropped(DragEvent event) {
    Dragboard db = event.getDragboard();
    if (db.hasImage()) {
        try {//from  w w  w  .  j  av  a 2  s. c om
            // Prompt for name & return file name
            File newOverlayFile = new File(currentDirectory.getCanonicalPath() + "/somefilename.png");
            ImageIO.write(SwingFXUtils.fromFXImage(db.getImage(), null), "png", newOverlayFile);
        } catch (IOException e) {
            log.error("Error writing new overlay image.", e);
        }

        loadImages(overlayTreeView.getSelectionModel().getSelectedItem());
        event.setDropCompleted(true);
    } else if (db.hasFiles()) {
        db.getFiles().forEach(file -> {
            FileSaveUtil.copyFile(file, currentDirectory);
        });
        loadImages(overlayTreeView.getSelectionModel().getSelectedItem());
        event.setDropCompleted(true);
    } else if (db.hasUrl()) {
        FileSaveUtil.copyFile(new File(db.getUrl()), currentDirectory);
        loadImages(overlayTreeView.getSelectionModel().getSelectedItem());
        event.setDropCompleted(true);
    }
}

From source file:be.makercafe.apps.makerbench.editors.GCodeEditor.java

private void handleExportAsPngFile(ActionEvent e) {

    if (csgObject == null) {
        Alert alert = new Alert(AlertType.ERROR);
        alert.setTitle("Oeps an error occured");
        alert.setHeaderText("Cannot export PNG. There is no geometry !");
        alert.setContentText("Please verify that your code generates a valid CSG object.");
        alert.showAndWait();/*from w ww.  j  a va2 s.c  om*/
        return;
    }

    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Export PNG File");
    fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image files (*.png)", "*.png"));

    File f = fileChooser.showSaveDialog(null);

    if (f == null) {
        return;
    }

    String fName = f.getAbsolutePath();

    if (!fName.toLowerCase().endsWith(".png")) {
        fName += ".png";
    }

    int snWidth = 1024;
    int snHeight = 1024;

    double realWidth = viewGroup.getBoundsInLocal().getWidth();
    double realHeight = viewGroup.getBoundsInLocal().getHeight();

    double scaleX = snWidth / realWidth;
    double scaleY = snHeight / realHeight;

    double scale = Math.min(scaleX, scaleY);

    PerspectiveCamera snCam = new PerspectiveCamera(false);
    snCam.setTranslateZ(-200);

    SnapshotParameters snapshotParameters = new SnapshotParameters();
    snapshotParameters.setTransform(new Scale(scale, scale));
    snapshotParameters.setCamera(snCam);
    snapshotParameters.setDepthBuffer(true);
    snapshotParameters.setFill(Color.TRANSPARENT);

    WritableImage snapshot = new WritableImage(snWidth, (int) (realHeight * scale));

    viewGroup.snapshot(snapshotParameters, snapshot);

    try {
        ImageIO.write(SwingFXUtils.fromFXImage(snapshot, null), "png", new File(fName));
    } catch (IOException ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
        Alert alert = new Alert(AlertType.ERROR);
        alert.setTitle("Oeps an error occured");
        alert.setHeaderText("Cannot export PNG. There went something wrong writing the file.");
        alert.setContentText(
                "Please verify that your file is not read only, is not locked by other user or program, you have enough diskspace.");
        alert.showAndWait();
    }
}