public static void setImageView(ImageView iv) { imageView = iv; angle = imageView.getRotate(); imageView.setRotate(0); image = SwingFXUtils.toFXImage( SwingFXUtils.fromFXImage(imageView.snapshot(null, null), null), null); }
/** @throws IOException error */ public final void loadImage() throws IOException { BufferedImage img; try { Stage stage = (Stage) Main.getWindow(); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open Image File"); 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); File f = fileChooser.showOpenDialog(stage); if (f != null) { logger.info(f.getName()); img = ImageIO.read(f); contactImage = new ContactImage(img); if ((contactImage.getHeight() >= 300 || contactImage.getHeight() <= 1000) && (contactImage.getWidth() >= 300 || contactImage.getWidth() <= 1000)) { contactImage.set(img); Image temp = SwingFXUtils.toFXImage(img, null); image.setImage(temp); } else { throw new ImageNotValidException("Foto ist zu groß!"); } } } catch (Exception e) { logger.log(Level.SEVERE, "Error: " + e.getMessage()); } }
public Optional<String> toImageBlock(Image image) { if (!current.currentPath().isPresent()) asciiDocController.saveDoc(); Path currentPath = current.currentPath().map(Path::getParent).get(); IOHelper.createDirectories(currentPath.resolve("images")); List<String> buffer = new LinkedList<>(); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(asciiDocController.getClipboardImageFilePattern()); Path path = Paths.get(dateTimeFormatter.format(LocalDateTime.now())); Path targetImage = currentPath.resolve("images").resolve(path.getFileName()); try { BufferedImage fromFXImage = SwingFXUtils.fromFXImage(image, null); ImageIO.write(fromFXImage, "png", targetImage.toFile()); } catch (Exception e) { logger.error("Problem occured while saving clipboard image {}", targetImage); } buffer.add(String.format("image::images/%s[]", path.getFileName())); if (buffer.size() > 0) return Optional.of(String.join("\n", buffer)); return Optional.empty(); }
private static Image jswingIconToImage(javax.swing.Icon jswingIcon) { BufferedImage bufferedImage = new BufferedImage( jswingIcon.getIconWidth(), jswingIcon.getIconHeight(), BufferedImage.TYPE_INT_ARGB); jswingIcon.paintIcon(null, bufferedImage.getGraphics(), 0, 0); return SwingFXUtils.toFXImage(bufferedImage, null); }
public static BufferedImage getScreenshot(WebView browser) { if (browser != null) { WritableImage returnimage = browser.snapshot(new SnapshotParameters(), null); return SwingFXUtils.fromFXImage(returnimage, null); } return null; }
public static BufferedImage fromNode(Node node) { final WritableImage jfx = node.snapshot(null, null); final BufferedImage img = new BufferedImage((int) jfx.getWidth(), (int) jfx.getHeight(), BufferedImage.TYPE_INT_ARGB); SwingFXUtils.fromFXImage(jfx, img); return img; }
private void saveImage() { try { // save ImageIO.write( SwingFXUtils.fromFXImage(imgPattern, null), "png", new File("pattern_" + width + "x" + height + ".png")); } catch (IOException ex) { System.out.println("Error saving image"); } }
/** * Saves a snapshot of an image to the users directory * * @param image the image to be saved * @param user the user to save the image to */ public static void SaveProfilePicture(Image image, User user) { String userDir = new File(Persistent.getProfileFilePath(user.getUserId())).getParent(); File file = new File(userDir + "/profile.png"); try { ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file); } catch (IOException e) { // file path doesn't exist // System.out.println("Couldn't save picture. filePath not found"); } }
public static Image convertFileToImage(File f) { Image image = null; try { BufferedImage bufferedImage = ImageIO.read(f); image = SwingFXUtils.toFXImage(bufferedImage, null); } catch (IOException ex) { } return image; }
@FXML public void compute() { double[][] transformedTrajectory = getTransformedTrajectory(); if (transformedTrajectory == null) return; // compute and display RP BufferedImage rp = DRQA.getRPImage( transformedTrajectory, transformedTrajectory, recurrenceThresholdSlider.getValue()); rpImageView.setImage(SwingFXUtils.toFXImage(rp, null)); applyImageScale(); // compute and display CRT DRQA.conditional_ww_limit = Integer.parseInt(crtLimit.getText()); DRQA.CRT_LOG_SCALE = logScaleCheckBox.isSelected(); drqa = new DRQA( transformedTrajectory, transformedTrajectory, recurrenceThresholdSlider.getValue()); BufferedImage crt = drqa.getCRTImage(DRQA.conditional_ww_limit, drqa.conditional_ww); crtImageView.setImage(SwingFXUtils.toFXImage(crt, null)); String[] stats = drqa.crtStatistics().split("\t"); crtStats.setText( String.format( "mean row: %.2f\tmean col: %.2f\ncorrelation: %.2f\nmax row: %s\tmax col: %s\nlocal maxima: %s\nentropy: %.2f", Double.parseDouble(stats[0]), Double.parseDouble(stats[1]), Double.parseDouble(stats[2]), stats[3], stats[4], stats[5], Double.parseDouble(stats[6]))); drqa.computeRQA(2, 2, 2); rqaMeasures.setText(drqa.printableString(DRQA.STANDARD_RQA)); updateTimeSeriesChart(); updateDistanceDistributionChart(); updateLineLengthHistogram( null, null, lineLengthTypeSelector.getSelectionModel().getSelectedIndex()); }
public static void saveCanvas(Canvas canvas, String name, String path) { int width = (int) canvas.getWidth(); int height = (int) canvas.getHeight(); WritableImage image = new WritableImage(width, height); canvas.snapshot(new SnapshotParameters(), image); File file = new File(name); try { ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file); } catch (Exception e) { e.printStackTrace(); } }
public static int[][] convertImageTo2DIntArray(Image image, int width, int height) { int[][] returnArray = new int[height][width]; // Obtain PixelReader PixelReader pixelReader = image.getPixelReader(); int xSegmentLength = divideAByBThenRoundDown(image.getWidth(), width); int ySegmentLength = divideAByBThenRoundDown(image.getHeight(), height); BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null); for (int row = 0; row < height; row++) { for (int column = 0; column < width; column++) { BufferedImage tempBufferedImage = bufferedImage.getSubimage( xSegmentLength * column, ySegmentLength * row, xSegmentLength, ySegmentLength); Color averageColor = AverageColorFinder.findAverageColorFromImage( SwingFXUtils.toFXImage(tempBufferedImage, null)); int argb = ((int) (averageColor.getOpacity() * 255) << 24) | ((int) (averageColor.getRed() * 255) << 16) | ((int) (averageColor.getGreen() * 255) << 8) | ((int) (averageColor.getBlue() * 255)); returnArray[row][column] = argb; } } return returnArray; }
@FXML private void onChooseButtonClicked() { FileChooser fileChooser = new FileChooser(); File file = fileChooser.showOpenDialog(null); Image image; try { BufferedImage bufferedImage = ImageIO.read(file); image = SwingFXUtils.toFXImage(bufferedImage, null); picturePreview.setImage(image); picturePath.setText(file.getAbsolutePath()); } catch (Exception img) { System.err.println("Problem reading image."); } }
@Override public void initialize(URL arg0, ResourceBundle arg1) { days.bind(viewModel.daysProperty()); targetLineSeries.dataProperty().bind(viewModel.targetLineDataProperty()); loggedHoursSeries.dataProperty().bind(viewModel.loggedHoursDataProperty()); burndownSeries.dataProperty().bind(viewModel.burndownDataProperty()); burndownChart.getData().addAll(targetLineSeries, loggedHoursSeries, burndownSeries); burndownChart.getXAxis().setAutoRanging(true); // style burndownChart.setLegendVisible(false); burndownChart.setAnimated(false); yAxis.setMinorTickVisible(false); exportHyperlink.setOnAction( event -> { burndownChart.snapshot( snapshotResult -> { WritableImage image = snapshotResult.getImage(); // https://community.oracle.com/thread/2450090?tstart=0 final FileChooser fileChooser = new FileChooser(); fileChooser .getExtensionFilters() .addAll( new FileChooser.ExtensionFilter("PNG Files", "*.png"), new FileChooser.ExtensionFilter("All Files", "*")); String organisationFilename = viewModel.organisationProperty().get().getSaveLocation().getName(); fileChooser.setInitialFileName( organisationFilename.substring(0, organisationFilename.lastIndexOf('.')) + ".png"); File file = fileChooser.showSaveDialog(burndownChart.getScene().getWindow()); try { if (file != null) { ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }, null, null); }); }
private void export() { FileChooser chooser = new FileChooser(); chooser .getExtensionFilters() .add( new FileChooser.ExtensionFilter( "Image file (png, jpg, gif)", "*.png", "*.jpg", "*.gif")); File file = chooser.showSaveDialog(Cyclist.cyclistStage); if (file != null) { WritableImage image = _chart.snapshot(new SnapshotParameters(), null); try { ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file); } catch (IOException e) { log.error("Error writing image to file: " + e.getMessage()); } } }
/** * Instantiates the tileSet images using an image selected by the user. Given the number of rows * that the user input at the program startup, this automatically calculates the positions of the * individual tile images, and sets the tileSize for all tiles. * * <p>Note: tiles must be designed to be squares. * * @param file The image file containing what will be the map tiles */ public void openTileSet(File file) { try { origTileImage = ImageIO.read(file); tileSize = (int) origTileImage.getHeight() / numTileRows; // Minus 1 because tileSet matrix starts at index 0 numTileColumns = (int) origTileImage.getWidth() / tileSize; tileSet = new BufferedImage[numTileRows][numTileColumns]; for (int row = 0; row < numTileRows; row++) { for (int col = 0; col < numTileColumns; col++) { tileSet[row][col] = origTileImage.getSubimage(col * tileSize, row * tileSize, tileSize, tileSize); } } } catch (Exception ex) { ex.printStackTrace(); } // add tileSet to tileMap so that it is shown on screen for (int i = 0; i < numTileRows; i++) { for (int j = 0; j < numTileColumns; j++) { Image image = SwingFXUtils.toFXImage(tileSet[i][j], null); ImageView imageView = new ImageView(image); imageView.setX(j * tileSize); imageView.setY(i * tileSize); imageView.setFitWidth(tileSize); imageView.setFitHeight(tileSize); tileMap.getChildren().add(imageView); } } // Make the first tile selected currentTile = 0; double tx = ((ImageView) tileMap.getChildren().get(0)).getX(); double ty = ((ImageView) tileMap.getChildren().get(0)).getY(); double tw = ((ImageView) tileMap.getChildren().get(0)).getFitWidth(); double th = ((ImageView) tileMap.getChildren().get(0)).getFitHeight(); tileOutline = new Rectangle(tx, ty, tw, th); tileOutline.setStroke(Color.RED); tileOutline.setFill(null); tileMap.getChildren().add(tileOutline); }
@FXML public void saveAsPng() { WritableImage image = GraphicPane.snapshot(new SnapshotParameters(), null); FileChooser fileChooser = new FileChooser(); // Set extension filter FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG"); fileChooser.getExtensionFilters().add(extFilterPNG); // TODO: probably use a file chooser here File fileF = fileChooser.showSaveDialog(this.mainApp.getPrimaryStage()); File file = new File(fileF.getAbsolutePath() + ".png"); try { ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file); } catch (IOException e) { // TODO: handle exception here } }
/** Adds the icon and name of application to the grid. */ private void addPlugins() { if (isPlugins()) { loadPlugins(); // Going through the plugin 2d Arraylist for (int i = 0; i < plugins.size(); i++) { File files; ImageView view; files = icons.get(i).get(0); if (!files.exists()) { view = new ImageView(defaultimage); } else { File[] listFiles = files.listFiles(); File file = listFiles[0]; Image image; try { BufferedImage bufimage = ImageIO.read(file); image = SwingFXUtils.toFXImage(bufimage, null); } catch (IOException ioe) { image = defaultimage; } view = new ImageView(image); } // adds name of application for each plugin. if (!change) { labels.add(new Label(newAppData.get(i).get(0))); } else { labels.add(new Label(appData.get(i).get(0))); } gridPane.add(labels.get(i), 1, i); // adds icon of application for each plugin view.setFitHeight(100); view.setPreserveRatio(true); iconsView.add(view); gridPane.add(view, 0, i); } } }
/** * Loads a map from file: converts the values from the passed int matrix into images given by the * tileSet. The value in the map is the tile number. The matrix is passed to this method by {@code * loadMap()} in the KeyPressedListener class. * * @param oldMap int matrix holding tile numbers that correspond to a specific tile. */ public void loadOldMap(int[][] oldMap) { constructedMap.getChildren().clear(); mapX = tileSize; mapY = tileSize; mapW = oldMap[0].length; mapH = oldMap.length; mapOutline.setX(mapX); mapOutline.setY(mapY); mapOutline.setWidth(mapW * tileSize); mapOutline.setHeight(mapH * tileSize); map = new int[mapH][mapW]; for (int row = 0; row < mapH; row++) { for (int col = 0; col < mapW; col++) { currentTile = map[row][col] = oldMap[row][col]; // Get the right tile from tileSet int tileRow = (int) currentTile / numTileColumns; int tileCol = currentTile % numTileColumns; // Get the right image Image image = SwingFXUtils.toFXImage(tileSet[tileRow][tileCol], null); ImageView imageView = new ImageView(image); // Add the selected tile to the screen double imageX = mapOutline.getX() + col * tileSize; double imageY = mapOutline.getY() + row * tileSize; imageView.setX(imageX); imageView.setY(imageY); imageView.setFitWidth(tileSize); imageView.setFitHeight(tileSize); updateConstructedMap(imageView); } } currentTile = 0; updateCurrentTile(); }
/** * Get contact information and display them. * * @throws IOException error */ public final void setupTextFields() throws IOException { String firstName; String lastName; String email; String phoneNumber; String city; String born; String zipCode; String street; String country; int houseNumber; firstName = c.getFirstName(); lastName = c.getLastName(); email = c.getEmail(); phoneNumber = c.getPhoneNumber(); born = c.getBirthday().toGMTString(); Image temp = SwingFXUtils.toFXImage(c.getPhoto().get(), null); image.setImage(temp); zipCode = c.getAddress().getZipCode(); city = c.getAddress().getCity(); houseNumber = c.getAddress().getHouseNumber(); street = c.getAddress().getStreet(); country = c.getAddress().getCountry(); this.txtFirstName.setText(firstName); this.txtLastName.setText(lastName); this.txtEmail.setText(email); this.txtPhoneNumber.setText(phoneNumber); this.txtCity.setText(city); this.txtHouseNumber.setText(String.valueOf(houseNumber)); this.txtBorn.setText(born); this.txtZipCode.setText(zipCode); this.txtStreet.setText(street); this.txtCountry.setText(country); }
private void createScreenShotButton() { screenShotButton = new Button(FontAwesome.ICON_CAMERA); screenShotButton.setFont(Font.font("FontAwesome", 14)); screenShotButton.setTooltip(new Tooltip("Take Screen Shot.")); // screenShotButton.disableProperty().bind(webEngine.getLoadWorker().runningProperty()); screenShotButton.setOnAction( observable -> { WritableImage image = masterPane.snapshot(null, null); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss'.png'"); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Save Screen Shot..."); fileChooser.setInitialFileName(simpleDateFormat.format(Date.from(Instant.now()))); File imageFile = fileChooser.showSaveDialog(null); if (imageFile != null) { try { ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", imageFile); } catch (IOException e) { e.printStackTrace(); } } }); }
/** * JavaFX event triggered when the user clicks the browse button to select a background image * * @param e the JavaFX event */ @FXML protected void browseImagePressed(ActionEvent e) { FileChooser fileChooser = new FileChooser(); // Create a new file chooser to allow the user to pick an image fileChooser.setTitle("Select an Image"); FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG"); // Set extension filter FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG"); fileChooser.getExtensionFilters().addAll(extFilterJPG, extFilterPNG); File imageFile = fileChooser.showOpenDialog(MainStage.getInstance().getPrimaryStage()); if (imageFile != null && imageFile.exists()) { try { BufferedImage bufferedImage = ImageIO.read(imageFile); Image image = SwingFXUtils.toFXImage(bufferedImage, null); MainStage.getInstance().getVideoPane().setBackground(image); } catch (IOException ex) { System.out.println("Error while loading the image"); } } }
@Override public void start(final Stage stage) { // AWT Image with red border final BufferedImage image = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics2D gc = image.createGraphics(); gc.setColor(Color.WHITE); gc.fillRect(0, 0, IMAGE_WIDTH - 1, IMAGE_HEIGHT - 1); gc.setColor(Color.RED); gc.drawRect(0, 0, IMAGE_WIDTH - 1, IMAGE_HEIGHT - 1); // Scale image final BufferedImage scaled = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); gc = scaled.createGraphics(); gc.drawImage(image, 0, 0, WIDTH, HEIGHT, null); // Draw scaled image into canvas final Canvas canvas = new Canvas(WIDTH, HEIGHT); canvas.getGraphicsContext2D().drawImage(SwingFXUtils.toFXImage(scaled, null), 0, 0); final Scene scene = new Scene(new Group(canvas), WIDTH, HEIGHT); stage.setScene(scene); stage.show(); }
// Converts the byte array to javafx image format public static Image bytesToImage(byte[] bytes) throws IOException { return SwingFXUtils.toFXImage(ImageIO.read(new ByteArrayInputStream(bytes)), null); }
private static Image getImage() { BufferedImage image = SwingFXUtils.fromFXImage(imageView.snapshot(null, null), null); return SwingFXUtils.toFXImage(image, null); }
@Override public void handle(MouseEvent e) { if (e.isPrimaryButtonDown()) { // If in bounds of the map if (e.getX() > mp.mapOutline.getX() && e.getY() > mp.mapOutline.getY() && e.getX() < mp.mapOutline.getX() + mp.mapOutline.getWidth() && e.getY() < mp.mapOutline.getY() + mp.mapOutline.getHeight()) { // Get the right tile from tileSet int tileRow = 0; int tileCol = 0; int selectionIndex = mp.currentTile; while (selectionIndex > mp.numTileColumns - 1) { selectionIndex = selectionIndex - mp.numTileColumns; tileRow++; } tileCol = selectionIndex; Image image = SwingFXUtils.toFXImage(mp.tileSet[tileRow][tileCol], null); ImageView imageView = new ImageView(image); // Save the currentTile to the map // int type-casting rounds x/y down -> tile placement on the map "grid" // This overwrites any previous tile number in the map matrix int mapCol = (int) (e.getX() - mp.mapOutline.getX()) / mp.tileSize; int mapRow = (int) (e.getY() - mp.mapOutline.getY()) / mp.tileSize; mp.map[mapRow][mapCol] = mp.currentTile; // Add the selected tile to the screen double imageX = mp.mapOutline.getX() + mapCol * mp.tileSize; double imageY = mp.mapOutline.getY() + mapRow * mp.tileSize; imageView.setX(imageX); imageView.setY(imageY); imageView.setFitWidth(mp.tileSize); imageView.setFitHeight(mp.tileSize); mp.updateConstructedMap(imageView); } // End if mouse inside map // Else if mouse inside tilePane // Not working yet because tileMap can't gain focus // and MapPane loses focus upon mouse leaving /*else if (e.getY() > mp.getHeight() - mp.tileSize*mp.numTileRows){ int col = (int) e.getX()/mp.tileSize; int row = (int) e.getY()/mp.tileSize; mp.currentTile = col + row*col; mp.updateCurrentTile(); } */ } // End if mouse is left button else if (e.isSecondaryButtonDown()) { if (e.getX() > mp.mapOutline.getX() && e.getY() > mp.mapOutline.getY() && e.getX() < mp.mapOutline.getX() + mp.mapOutline.getWidth() && e.getY() < mp.mapOutline.getY() + mp.mapOutline.getHeight()) { // Get the empty image Image image = SwingFXUtils.toFXImage(mp.tileSet[0][0], null); ImageView imageView = new ImageView(image); // Save to map int mapCol = (int) (e.getX() - mp.mapOutline.getX()) / mp.tileSize; int mapRow = (int) (e.getY() - mp.mapOutline.getY()) / mp.tileSize; mp.map[mapRow][mapCol] = 0; // Add the selected tile to the screen double imageX = mp.mapOutline.getX() + mapCol * mp.tileSize; double imageY = mp.mapOutline.getY() + mapRow * mp.tileSize; imageView.setX(imageX); imageView.setY(imageY); imageView.setFitWidth(mp.tileSize); imageView.setFitHeight(mp.tileSize); mp.updateConstructedMap(imageView); } // End if mouse inside map } // End else if } // End handle