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:Main.java

public static void saveToFile(Image image) {
    File outputFile = new File("C:/JavaFX/");
    BufferedImage bImage = SwingFXUtils.fromFXImage(image, null);
    try {//from   w  ww  .  j  a v  a 2 s .  c  o  m
        ImageIO.write(bImage, "png", outputFile);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.geopoke.WorldMap.java

/**
     * Get a snapshot of the current map as an image.
     * <p/>//from  w ww.j ava2 s .co m
     * @return the current snapshot of the map.
     */
    public BufferedImage getSnapshot() {
        BufferedImage image = SwingFXUtils.fromFXImage(getScene().snapshot(null), null);
        Bounds bounds = localToScene(getLayoutBounds());
        return image.getSubimage((int) bounds.getMinX(), (int) bounds.getMinY(), (int) getWidth(),
                (int) getHeight());
    }

From source file:editeurpanovisu.ReadWriteImage.java

public static void writeTiff(Image imgImage, String strNomFich, boolean bSharpen, float sharpenLevel)
        throws ImageReadException, IOException {
    File file = new File(strNomFich);
    BufferedImage imageRGBSharpen = null;
    BufferedImage imageRGB = SwingFXUtils.fromFXImage(imgImage, null);

    Graphics2D graphics = imageRGB.createGraphics();
    graphics.drawImage(imageRGB, 0, 0, null);
    if (bSharpen) {
        imageRGBSharpen = new BufferedImage(imageRGB.getWidth(), imageRGB.getHeight(),
                BufferedImage.TYPE_INT_RGB);
        Kernel kernel = new Kernel(3, 3, sharpenMatrix);
        ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        cop.filter(imageRGB, imageRGBSharpen);
    }//from   w ww.ja  va  2 s .c  o  m

    final ImageFormat format = ImageFormats.TIFF;
    final Map<String, Object> params = new HashMap<>();
    params.put(ImagingConstants.PARAM_KEY_COMPRESSION,
            new Integer(TiffConstants.TIFF_COMPRESSION_UNCOMPRESSED));

    if (bSharpen) {
        try {
            Imaging.writeImage(imageRGBSharpen, file, format, params);
        } catch (ImageWriteException ex) {
            Logger.getLogger(ReadWriteImage.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        try {
            Imaging.writeImage(imageRGB, file, format, params);
        } catch (ImageWriteException ex) {
            Logger.getLogger(ReadWriteImage.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:editeurpanovisu.ReadWriteImage.java

public static Image resizeImage(Image img, int newW, int newH) {
    BufferedImage image = SwingFXUtils.fromFXImage(img, null);

    try {/*from w w w .j  av a  2 s  .  c  o m*/
        BufferedImage imgRetour = Thumbnails.of(image).size(newW, newH).asBufferedImage();
        return SwingFXUtils.toFXImage(imgRetour, null);
    } catch (IOException ex) {
        Logger.getLogger(ReadWriteImage.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:org.sleuthkit.autopsy.timeline.actions.SaveSnapshotAsReport.java

/**
 * Constructor//  w  ww  . j  a  v  a 2s.  c  o m
 *
 * @param controller   The controller for this timeline action
 * @param nodeSupplier The Supplier of the node to snapshot.
 */
@NbBundle.Messages({ "Timeline.ModuleName=Timeline", "SaveSnapShotAsReport.action.dialogs.title=Timeline",
        "SaveSnapShotAsReport.action.name.text=Snapshot Report",
        "SaveSnapShotAsReport.action.longText=Save a screen capture of the current view of the timeline as a report.",
        "# {0} - report file path", "SaveSnapShotAsReport.ReportSavedAt=Report saved at [{0}]",
        "SaveSnapShotAsReport.Success=Success",
        "SaveSnapShotAsReport.FailedToAddReport=Failed to add snaphot to case as a report.",
        "# {0} - report path", "SaveSnapShotAsReport.ErrorWritingReport=Error writing report to disk at {0}.",
        "# {0} - generated default report name",
        "SaveSnapShotAsReport.reportName.prompt=leave empty for default report name: {0}.",
        "SaveSnapShotAsReport.reportName.header=Enter a report name for the Timeline Snapshot Report.",
        "SaveSnapShotAsReport.duplicateReportNameError.text=A report with that name already exists." })
public SaveSnapshotAsReport(TimeLineController controller, Supplier<Node> nodeSupplier) {
    super(Bundle.SaveSnapShotAsReport_action_name_text());
    setLongText(Bundle.SaveSnapShotAsReport_action_longText());
    setGraphic(new ImageView(SNAP_SHOT));

    this.controller = controller;
    this.currentCase = controller.getAutopsyCase();

    setEventHandler(actionEvent -> {
        //capture generation date and use to make default report name
        Date generationDate = new Date();
        final String defaultReportName = FileUtil.escapeFileName(currentCase.getName() + " "
                + new SimpleDateFormat("MM-dd-yyyy-HH-mm-ss").format(generationDate)); //NON_NLS
        BufferedImage snapshot = SwingFXUtils.fromFXImage(nodeSupplier.get().snapshot(null, null), null);

        //prompt user to pick report name
        TextInputDialog textInputDialog = new TextInputDialog();
        PromptDialogManager.setDialogIcons(textInputDialog);
        textInputDialog.setTitle(Bundle.SaveSnapShotAsReport_action_dialogs_title());
        textInputDialog.getEditor()
                .setPromptText(Bundle.SaveSnapShotAsReport_reportName_prompt(defaultReportName));
        textInputDialog.setHeaderText(Bundle.SaveSnapShotAsReport_reportName_header());

        //keep prompt even if text field has focus, until user starts typing.
        textInputDialog.getEditor()
                .setStyle("-fx-prompt-text-fill: derive(-fx-control-inner-background, -30%);");//NON_NLS 

        /*
         * Create a ValidationSupport to validate that a report with the
         * entered name doesn't exist on disk already. Disable ok button if
         * report name is not validated.
         */
        ValidationSupport validationSupport = new ValidationSupport();
        validationSupport.registerValidator(textInputDialog.getEditor(), false, new Validator<String>() {
            @Override
            public ValidationResult apply(Control textField, String enteredReportName) {
                String reportName = StringUtils.defaultIfBlank(enteredReportName, defaultReportName);
                boolean exists = Files.exists(Paths.get(currentCase.getReportDirectory(), reportName));
                return ValidationResult.fromErrorIf(textField,
                        Bundle.SaveSnapShotAsReport_duplicateReportNameError_text(), exists);
            }
        });
        textInputDialog.getDialogPane().lookupButton(ButtonType.OK).disableProperty()
                .bind(validationSupport.invalidProperty());

        //show dialog and handle result
        textInputDialog.showAndWait().ifPresent(enteredReportName -> {
            //reportName defaults to case name + timestamp if left blank
            String reportName = StringUtils.defaultIfBlank(enteredReportName, defaultReportName);
            Path reportFolderPath = Paths.get(currentCase.getReportDirectory(), reportName,
                    "Timeline Snapshot"); //NON_NLS
            Path reportMainFilePath;

            try {
                //generate and write report
                reportMainFilePath = new SnapShotReportWriter(currentCase, reportFolderPath, reportName,
                        controller.getEventsModel().getZoomParamaters(), generationDate, snapshot)
                                .writeReport();
            } catch (IOException ex) {
                LOGGER.log(Level.SEVERE, "Error writing report to disk at " + reportFolderPath, ex); //NON_NLS
                new Alert(Alert.AlertType.ERROR,
                        Bundle.SaveSnapShotAsReport_ErrorWritingReport(reportFolderPath)).show();
                return;
            }

            try {
                //add main file as report to case
                Case.getCurrentCase().addReport(reportMainFilePath.toString(), Bundle.Timeline_ModuleName(),
                        reportName);
            } catch (TskCoreException ex) {
                LOGGER.log(Level.WARNING,
                        "Failed to add " + reportMainFilePath.toString() + " to case as a report", ex); //NON_NLS
                new Alert(Alert.AlertType.ERROR, Bundle.SaveSnapShotAsReport_FailedToAddReport()).show();
                return;
            }

            //notify user of report location
            final Alert alert = new Alert(Alert.AlertType.INFORMATION, null, OPEN, OK);
            alert.setTitle(Bundle.SaveSnapShotAsReport_action_dialogs_title());
            alert.setHeaderText(Bundle.SaveSnapShotAsReport_Success());

            //make action to open report, and hyperlinklable to invoke action
            final OpenReportAction openReportAction = new OpenReportAction(reportMainFilePath);
            HyperlinkLabel hyperlinkLabel = new HyperlinkLabel(
                    Bundle.SaveSnapShotAsReport_ReportSavedAt(reportMainFilePath.toString()));
            hyperlinkLabel.setOnAction(openReportAction);
            alert.getDialogPane().setContent(hyperlinkLabel);

            alert.showAndWait().filter(OPEN::equals).ifPresent(buttonType -> openReportAction.handle(null));
        });
    });
}

From source file:editeurpanovisu.ReadWriteImage.java

/**
 *
 * @param img/*from w  w w .  ja  va  2s .co  m*/
 * @param destFile
 * @param quality
 * @param sharpen
 * @param sharpenLevel
 * @throws IOException
 */
public static void writeJpeg(Image img, String destFile, float quality, boolean sharpen, float sharpenLevel)
        throws IOException {
    sharpenMatrix = calculeSharpenMatrix(sharpenLevel);
    BufferedImage imageRGBSharpen = null;
    IIOImage iioImage = null;
    BufferedImage image = SwingFXUtils.fromFXImage(img, null); // Get buffered image.

    BufferedImage imageRGB = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.OPAQUE); // Remove alpha-channel from buffered image.

    Graphics2D graphics = imageRGB.createGraphics();
    graphics.drawImage(image, 0, 0, null);
    if (sharpen) {
        imageRGBSharpen = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
        Kernel kernel = new Kernel(3, 3, sharpenMatrix);
        ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        cop.filter(imageRGB, imageRGBSharpen);
    }
    ImageWriter writer = null;
    FileImageOutputStream output = null;
    try {
        writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(quality);
        output = new FileImageOutputStream(new File(destFile));
        writer.setOutput(output);
        if (sharpen) {
            iioImage = new IIOImage(imageRGBSharpen, null, null);
        } else {
            iioImage = new IIOImage(imageRGB, null, null);
        }
        writer.write(null, iioImage, param);
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (output != null) {
            output.close();
        }
    }
    graphics.dispose();
}

From source file:editeurpanovisu.ReadWriteImage.java

/**
 *
 * @param img//from   w  w w .  j  a  va2 s .c o m
 * @param destFile
 * @param sharpen
 * @param sharpenLevel
 * @throws IOException
 */
public static void writeBMP(Image img, String destFile, boolean sharpen, float sharpenLevel)
        throws IOException {
    sharpenMatrix = calculeSharpenMatrix(sharpenLevel);
    BufferedImage imageRGBSharpen = null;
    IIOImage iioImage = null;

    BufferedImage image = SwingFXUtils.fromFXImage(img, null); // Get buffered image.
    BufferedImage imageRGB = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.OPAQUE); // Remove alpha-channel from buffered image.

    Graphics2D graphics = imageRGB.createGraphics();
    graphics.drawImage(image, 0, 0, null);
    if (sharpen) {

        imageRGBSharpen = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
        Kernel kernel = new Kernel(3, 3, sharpenMatrix);
        ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        cop.filter(imageRGB, imageRGBSharpen);
    }
    ImageWriter writer = null;
    FileImageOutputStream output = null;
    try {
        writer = ImageIO.getImageWritersByFormatName("bmp").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        output = new FileImageOutputStream(new File(destFile));
        writer.setOutput(output);
        if (sharpen) {
            iioImage = new IIOImage(imageRGBSharpen, null, null);
        } else {
            iioImage = new IIOImage(imageRGB, null, null);
        }
        writer.write(null, iioImage, param);
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (output != null) {
            output.close();
        }
    }
    graphics.dispose();
}

From source file:net.rptools.assets.supplier.AbstractURIAssetSupplier.java

/**
 * Handle output stream and notify the asset upon completion. <b>This closes
 * the stream.</b>/*from  w  w w .jav  a  2 s.c  o  m*/
 * @param id id of asset
 * @param obj asset itself
 * @param listener listener to inform upon completion
 * @param stream output stream to write to. Will be closed.
 * @throws IOException I/O problems
 */
@ThreadPolicy(ThreadPolicy.ThreadId.ANY)
protected void handleOutputStream(final String id, final Asset obj, final AssetListener listener,
        final OutputStream stream) throws IOException {
    try (final OutputStream outputStream = new OutputStreamInterceptor(getComponent().getFramework(), id, -1L,
            stream, listener, getNotifyInterval())) {
        switch (obj.getType()) {
        case IMAGE:
            final Image img = (Image) obj.getMain();
            ImageIO.write(SwingFXUtils.fromFXImage(img, null), "PNG", outputStream);
            break;
        case TEXT:
            final String txt = (String) obj.getMain();
            outputStream.write(txt.getBytes(StandardCharsets.UTF_8));
            break;
        default: // This should not happen. Messing with the constants, renders assets non-writable
            break;
        }
    }
    if (listener != null) {
        listener.notify(id, obj);
    }
}

From source file:com.adr.mimame.PlatformList.java

public Image getCachedImage(String url) {

    if (url == null) {
        return null;
    } else if (!"http".equalsIgnoreCase(url.substring(0, 4)) && !"ftp".equalsIgnoreCase(url.substring(0, 3))) {
        // a local image
        return new Image(url, true);
    } else {//from  w  w w.  ja v a2  s  . c om
        // a remote image
        try {
            File cachedir = new File(mimamememuhome, "IMGCACHE");
            FileUtils.forceMkdir(cachedir);

            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(url.getBytes("UTF-8"));
            String cachefilename = Base64.getUrlEncoder().encodeToString(md.digest());
            File cachefile = new File(cachedir, cachefilename + ".png");
            File cachefilenull = new File(cachedir, cachefilename + ".null");

            if (cachefilenull.exists()) {
                return null;
            } else if (cachefile.exists()) {
                return new Image(cachefile.toURI().toURL().toString(), true);
            } else {
                Image img = new Image(url, true);
                img.progressProperty().addListener(
                        (ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
                            if (newValue.doubleValue() == 1.0) {
                                exec.execute(() -> {
                                    try {
                                        if (img.isError()) {
                                            cachefilenull.createNewFile();
                                        } else {
                                            ImageIO.write(SwingFXUtils.fromFXImage(img, null), "png",
                                                    cachefile);
                                        }
                                    } catch (IOException ex) {
                                        logger.log(Level.SEVERE, "Cannot save image cache.", ex);
                                    }
                                });
                            }
                        });
                return img;
            }
        } catch (IOException | NoSuchAlgorithmException ex) {
            logger.log(Level.SEVERE, "Cannot create image cache.", ex);
            return new Image(url);
        }
    }
}

From source file:editeurpanovisu.ReadWriteImage.java

/**
 *
 * @param img//from  w ww  .ja  v  a 2 s . c  om
 * @param destFile
 * @param sharpen
 * @param sharpenLevel
 * @throws IOException
 */
public static void writePng(Image img, String destFile, boolean sharpen, float sharpenLevel)
        throws IOException {
    sharpenMatrix = calculeSharpenMatrix(sharpenLevel);
    BufferedImage imageRGBSharpen = null;
    IIOImage iioImage = null;
    BufferedImage image = SwingFXUtils.fromFXImage(img, null); // Get buffered image.
    BufferedImage imageRGB = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.BITMASK);
    Graphics2D graphics = imageRGB.createGraphics();
    graphics.drawImage(image, 0, 0, null);
    if (sharpen) {
        imageRGBSharpen = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
        Kernel kernel = new Kernel(3, 3, sharpenMatrix);
        ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        cop.filter(imageRGB, imageRGBSharpen);
    }
    ImageWriter writer = null;
    FileImageOutputStream output = null;
    try {
        writer = ImageIO.getImageWritersByFormatName("png").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        output = new FileImageOutputStream(new File(destFile));
        writer.setOutput(output);
        if (sharpen) {
            iioImage = new IIOImage(imageRGBSharpen, null, null);
        } else {
            iioImage = new IIOImage(imageRGB, null, null);
        }
        writer.write(null, iioImage, param);
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (output != null) {
            output.close();
        }
    }
    graphics.dispose();
}