Example usage for javafx.embed.swing SwingFXUtils toFXImage

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

Introduction

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

Prototype

public static WritableImage toFXImage(BufferedImage bimg, WritableImage wimg) 

Source Link

Document

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

Usage

From source file:editeurpanovisu.ReadWriteImage.java

public static Image readTiff(String strNomFich) throws ImageReadException, IOException {
    File file = new File(strNomFich);
    final Map<String, Object> params = new HashMap<>();

    params.put(ImagingConstants.BUFFERED_IMAGE_FACTORY, new ManagedImageBufferedImageFactory());

    final BufferedImage img = Imaging.getBufferedImage(file, params);

    Image image = SwingFXUtils.toFXImage(img, null);

    return image;
}

From source file:com.inbook.resource.PngSprite.java

public Image getIcon(BufferedImage source, int width, int height, String iconName) {
    int position = positions.get(iconName);
    BufferedImage subimage = source.getSubimage(0, position * height, width, height);
    return SwingFXUtils.toFXImage(subimage, null);
}

From source file:javafx1.JavaFX1.java

@Override
    public void setBild(byte[] xb) {

        if (xb == null) {
            primaryStage.setTitle("Empfange null");
        } else {/* w w w. ja  v a 2 s  . c  o  m*/
            primaryStage.setTitle(xb.length + " byte, " + new Date());
            // System.out.println(new String(xb));

            try {

                String base64String = new String(xb);
                // rckwandeln von base64
                byte[] backToBytes = Base64.decodeBase64(base64String);
                InputStream in = new ByteArrayInputStream(backToBytes);
                BufferedImage bi;
                bi = ImageIO.read(in);
                if (bi == null) {
                    System.out.println(" Bild=NULL ");
                } else {
                    //BufferedImage bi2 = analyzePic(bi);
                    Image img = SwingFXUtils.toFXImage(bi, null);
                    imgpic.setImage(img);

                    img = analyzePic(bi);
                    imgpic1.setImage(img);

                }

            } catch (Exception ex) {
                Logger.getLogger(JavaFX1.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   www  .ja v  a2s. 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:net.rptools.tokentool.util.ImageUtil.java

private static ImageView getImage(ImageView thumbView, final Path filePath, final boolean overlayWanted,
        final int THUMB_SIZE) throws IOException {
    Image thumb = null;//from  ww w.ja v  a  2s.  com
    String fileURL = filePath.toUri().toURL().toString();

    if (ImageUtil.SUPPORTED_IMAGE_FILE_FILTER.accept(null, fileURL)) {
        if (THUMB_SIZE <= 0)
            thumb = processMagenta(new Image(fileURL), COLOR_THRESHOLD, overlayWanted);
        else
            thumb = processMagenta(new Image(fileURL, THUMB_SIZE, THUMB_SIZE, true, true), COLOR_THRESHOLD,
                    overlayWanted);
    } else if (ImageUtil.PSD_FILE_FILTER.accept(null, fileURL)) {
        ImageInputStream is = null;
        PSDImageReader reader = null;
        int imageIndex = 1;

        // Mask layer should always be layer 1 and overlay image on layer 2. Note, layer 0 will be a combined layer composite
        if (overlayWanted)
            imageIndex = 2;

        File file = filePath.toFile();

        try {
            is = ImageIO.createImageInputStream(file);
            if (is == null || is.length() == 0) {
                log.info("Image from file " + file.getAbsolutePath() + " is null");
            }

            Iterator<ImageReader> iterator = ImageIO.getImageReaders(is);
            if (iterator == null || !iterator.hasNext()) {
                throw new IOException("Image file format not supported by ImageIO: " + filePath);
            }

            reader = (PSDImageReader) iterator.next();
            reader.setInput(is);
            BufferedImage thumbBI;
            thumbBI = reader.read(imageIndex);

            if (thumbBI != null) {
                int layerIndex = 0;
                if (overlayWanted)
                    layerIndex = 1;

                IIOMetadata metadata = reader.getImageMetadata(0);
                IIOMetadataNode root = (IIOMetadataNode) metadata
                        .getAsTree(PSDMetadata.NATIVE_METADATA_FORMAT_NAME);
                NodeList layerInfos = root.getElementsByTagName("LayerInfo");

                // Layer index corresponds to imageIndex - 1 in the reader
                IIOMetadataNode layerInfo = (IIOMetadataNode) layerInfos.item(layerIndex);

                // Get the width & height of the Mask layer so we can create the overlay the same size
                int width = reader.getWidth(0);
                int height = reader.getHeight(0);

                // Get layer offsets, PhotoShop PSD layers can have different widths/heights and all images start at 0,0 with a layer offset applied
                int x = Math.max(Integer.parseInt(layerInfo.getAttribute("left")), 0);
                int y = Math.max(Integer.parseInt(layerInfo.getAttribute("top")), 0);

                // Lets pad the overlay with transparency to make it the same size as the PSD canvas size
                thumb = resizeCanvas(SwingFXUtils.toFXImage(thumbBI, null), width, height, x, y);

                // Finally set ImageView to thumbnail size
                if (THUMB_SIZE > 0) {
                    thumbView.setFitWidth(THUMB_SIZE);
                    thumbView.setPreserveRatio(true);
                }
            }
        } catch (Exception e) {
            log.error("Processing: " + file.getAbsolutePath(), e);
        } finally {
            // Dispose reader in finally block to avoid memory leaks
            reader.dispose();
            is.close();
        }
    }

    thumbView.setImage(thumb);

    return thumbView;
}

From source file:com.imesha.imageprocessor.controllers.MainController.java

/**
 * Show a given BufferedImage in the UI.
 *
 * @param bufferedImage The image to be shown in the UI
 * @param imageView     The JavaFX ImageView element in which the BufferedImage to be shown.
 *///w  w  w.  ja  v a 2s .c o m
private static void showImageInUI(final BufferedImage bufferedImage, final ImageView imageView) {
    Platform.runLater(new Runnable() {
        public void run() {
            Image loadedImage = SwingFXUtils.toFXImage(bufferedImage, null);
            imageView.setImage(loadedImage);
            imageView.setPreserveRatio(true);
            imageView.setSmooth(true);
            imageView.setCache(true);
        }
    });
}

From source file:javafx1.JavaFX1.java

public Image bildLaden() {
        Image zwischenBild = null;

        try {// ww  w.ja v  a 2  s.  c  om
            File input = new File("D:/_piCam/bild.jpg");
            //FileInputStream bi = ImageIO.read(input);
            BufferedImage bi = ImageIO.read(input);

            byte[] data = ((DataBufferByte) bi.getRaster().getDataBuffer()).getData();
            Mat mat = new Mat(bi.getHeight(), bi.getWidth(), CvType.CV_8UC3);
            mat.put(0, 0, data);

            Mat bild = new Mat(bi.getHeight(), bi.getWidth(), CvType.CV_8UC1);
            Imgproc.cvtColor(mat, bild, Imgproc.COLOR_BGR2GRAY);

            byte[] data1 = new byte[bild.rows() * bild.cols() * (int) (bild.elemSize())];
            bild.get(0, 0, data1);
            BufferedImage image1 = new BufferedImage(bild.cols(), bild.rows(), BufferedImage.TYPE_BYTE_GRAY);
            image1.getRaster().setDataElements(0, 0, bild.cols(), bild.rows(), data1);

            File ouptut = new File("D:/xml/grayscale2.jpg");
            //ImageIO.write(image1, "jpg", ouptut);
            BufferedImage gray = image1.getSubimage(0, 0, image1.getTileWidth(), image1.getHeight());
            zwischenBild = SwingFXUtils.toFXImage(gray, null);

        } catch (IOException ex) {
            System.out.println("Fehler beim Bild laden...");
        }
        return zwischenBild;
    }

From source file:org.cidte.sii.negocio.LogInManager.java

public Image getLogo() {
    ArrayList<Organizacion> all = conOrg.getAll();

    if (all == null || all.isEmpty()) {
        return new Image("/org/cidte/sii/imagenes/empty.png");
    } else {//  w ww.ja va2 s.com
        Organizacion org = all.get(0);
        if (org.getLogo() == null || org.getLogo().length < 1) {
            return new Image("/org/cidte/sii/imagenes/empty.png");
        }
        try {
            InputStream in = new ByteArrayInputStream(org.getLogo());
            BufferedImage bImageFromConvert = ImageIO.read(in);
            WritableImage image = SwingFXUtils.toFXImage(bImageFromConvert, null);
            return image;
        } catch (IOException e) {
            System.out.println("Error en covertir imagen " + e);
            return new Image("/org/cidte/sii/imagenes/empty.png");
        }
    }
}

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

/**
 * use Swing to generate and save a thumbnail for the given file
 *
 * @param file/*  w  ww.  ja  va  2  s . c  o  m*/
 *
 * @return a thumbnail generated for the given file, or {@code null} if a
 *         thumbnail could not be generated
 */
private Image fallbackToSwingImage(final DrawableFile<?> file) {
    final BufferedImage generateSwingIcon = generateSwingThumbnail(file);
    if (generateSwingIcon == null) { //if swing failed,
        return null; //propagate failure up cal stack.
    } else {//Swing load succeeded, convert to JFX Image
        final WritableImage toFXImage = SwingFXUtils.toFXImage(generateSwingIcon, null);
        if (toFXImage != null) { //if conversion succeeded save to disk cache
            imageSaver.execute(() -> {
                saveIcon(file, toFXImage);
            });
        }
        return toFXImage; //could be null
    }
}

From source file:snpviewer.SnpViewer.java

public void drawCoordinatesWithIterator(final SnpFile sfile, final Pane pane, final String pngPath,
        final Iterator<SnpFile> sIter, final Iterator<Pane> pIter, final int currentFile, final int totalFiles,
        final String chrom, final Double start, final Double end, final boolean forceRedraw,
        final SplitPane splitPane) {
    Stage stage = (Stage) splitPane.getScene().getWindow();
    fixStageSize(stage, true);//w  w w  .  java 2s . c o  m

    //stage.setResizable(false);//we have to disable this when using windows due to a bug (in javafx?)
    File pngFile = new File(sfile.getOutputDirectoryName() + "/" + chrom + ".png");
    if (pngPath != null && pngPath.length() > 0) {
        pngFile = new File(sfile.getOutputDirectoryName() + "/" + pngPath + "/" + chrom + ".png");
    }
    if (!forceRedraw && pngFile.exists()) {
        try {
            progressBar.progressProperty().unbind();
            progressBar.setProgress((double) currentFile / (double) totalFiles);
            BufferedImage bufferedImage = ImageIO.read(pngFile);
            Image image = SwingFXUtils.toFXImage(bufferedImage, null);
            ImageView chromImage = new ImageView(image);
            //chromImage.setCache(true);
            pane.getChildren().clear();
            pane.getChildren().add(chromImage);
            //pane.setCache(true);
            chromImage.fitWidthProperty().bind(pane.widthProperty());
            chromImage.fitHeightProperty().bind(pane.heightProperty());
            pane.minHeightProperty().bind(splitPane.heightProperty().divide(totalFiles));
            pane.minWidthProperty().bind(splitPane.widthProperty());

            if (sIter.hasNext()) {
                SnpFile nextFile = sIter.next();
                Pane nextPane = pIter.next();
                drawCoordinatesWithIterator(nextFile, nextPane, pngPath, sIter, pIter, currentFile + 1,
                        totalFiles, chrom, start, end, forceRedraw, splitPane);
            } else {
                progressBar.progressProperty().unbind();
                progressBar.setProgress(0);
                setProgressMode(false);
                fixStageSize(stage, false);//for windows only
                stage.setResizable(true);
            }
        } catch (IOException ex) {
            Dialogs.showErrorDialog(null, "IO error reading cached image", "Error displaying chromosome image",
                    "SnpViewer", ex);
            return;
        }

    } else {

        final DrawSnpsToPane draw = new DrawSnpsToPane(pane, sfile, chrom, Colors.aa.value, Colors.bb.value,
                Colors.ab.value, start, end);

        progressBar.progressProperty().unbind();
        //progressBar.setProgress(0);
        //progressBar.progressProperty().bind(draw.progressProperty());
        progressTitle.setText("Drawing " + currentFile + " of " + totalFiles);
        progressMessage.textProperty().bind(draw.messageProperty());
        cancelButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                draw.cancel();
            }
        });

        draw.setOnCancelled(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {

                progressBar.progressProperty().unbind();
                progressBar.setProgress(0);
                progressTitle.setText("Drawing Cancelled");
                progressMessage.textProperty().unbind();
                progressMessage.setText("Drawing Cancelled");
                setProgressMode(false);
                selectionOverlayPane.getChildren().clear();
                selectionOverlayPane.getChildren().add(dragSelectRectangle);
                Stage stage = (Stage) splitPane.getScene().getWindow();
                stage.setResizable(true);
                fixStageSize(stage, false);//for windows only
            }
        });
        draw.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                ArrayList<HashMap<String, Double>> result = (ArrayList<HashMap<String, Double>>) t.getSource()
                        .getValue();
                progressBar.progressProperty().unbind();
                progressBar.setProgress((double) currentFile / (2 * (double) totalFiles));
                progressTitle.setText("");
                progressMessage.textProperty().unbind();
                progressMessage.setText("");
                /*if (pane.getMinHeight() < 200){
                pane.setMinHeight(200);
                }
                if (pane.getMinWidth() < 800){
                    pane.setMinWidth(800);
                }*/
                if (result != null) {
                    List<Line> lines = drawLinesToPane(pane, result);
                    pane.getChildren().addAll(lines);
                    pane.setVisible(true);
                    convertSampleViewToImage(sfile, pane, chrom, pngPath);
                    /*for (Line l: lines){
                        l.startXProperty().unbind();
                        l.startYProperty().unbind();
                        l.endXProperty().unbind();
                        l.endYProperty().unbind();
                    }*/
                    lines.clear();
                }
                progressBar.setProgress((double) currentFile / (double) totalFiles);
                pane.minWidthProperty().bind(splitPane.widthProperty());
                pane.minHeightProperty().bind(splitPane.heightProperty().divide(totalFiles));
                // pane.setCache(true);
                if (sIter.hasNext()) {
                    SnpFile nextFile = sIter.next();
                    Pane nextPane = pIter.next();
                    drawCoordinatesWithIterator(nextFile, nextPane, pngPath, sIter, pIter, currentFile + 1,
                            totalFiles, chrom, start, end, forceRedraw, splitPane);
                } else {
                    setProgressMode(false);
                    progressBar.progressProperty().unbind();
                    progressBar.setProgress(0);

                    Stage stage = (Stage) splitPane.getScene().getWindow();
                    stage.setResizable(true);
                    fixStageSize(stage, false);//for windows only
                }
            }
        });
        draw.setOnFailed(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                draw.reset();
                progressBar.progressProperty().unbind();
                progressBar.setProgress(0);
                progressTitle.setText("ERROR!");
                progressMessage.textProperty().unbind();
                progressMessage.setText("Drawing failed!");
                setProgressMode(false);
                selectionOverlayPane.getChildren().clear();
                selectionOverlayPane.getChildren().add(dragSelectRectangle);
                //     Stage stage = (Stage) chromSplitPane.getScene().getWindow();
                //     stage.setResizable(true);
            }

        });
        draw.start();
    }
}