/** * Takes a snapshot of a canvas and saves it to the destination. * <p> * After the screenshot is taken it shows a dialogue to the user indicating the location of the snapshot. * * @param canvas a JavaFX {@link Canvas} object * @return the destination of the screenshot */ public String take(final Canvas canvas) { final WritableImage writableImage = new WritableImage((int) canvas.getWidth(), (int) canvas.getHeight()); final WritableImage snapshot = canvas.snapshot(new SnapshotParameters(), writableImage); try { ImageIO.write(SwingFXUtils.fromFXImage(snapshot, null), FILE_FORMAT, destination); new InformationDialogue( "Snapshot taken", "You can find your snapshot here: " + destination.getAbsolutePath() ).show(); } catch (final IOException e) { LOGGER.error("Snapshot could not be taken.", e); new ErrorDialogue(e).show(); } return destination.getAbsolutePath(); }
private static void renderImage(WritableImage img, double gridSize, double hueFactor, double hueOffset) { PixelWriter pw = img.getPixelWriter(); double w = img.getWidth(); double h = img.getHeight(); double xRatio = 0.0; double yRatio = 0.0; double hue = 0.0; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { xRatio = x/w; yRatio = y/h; hue = Math.sin(yRatio*(gridSize*Math.PI))*Math.sin(xRatio*(gridSize*Math.PI))*Math.tan(hueFactor/20.0)*360.0 + hueOffset; Color c = Color.hsb(hue, 1.0, 1.0); pw.setColor(x, y, c); } } }
/** * Converts charts to Java {@link WritableImage}s * * @param charts the charts to be converted to {@link WritableImage}s * @return a {@link List} of {@link WritableImage}s */ private List<WritableImage> chartsToImages(List<Chart> charts) { List<WritableImage> chartImages = new ArrayList<>(); // Scaling the chart image gives it a higher resolution // which results in a better image quality when the // image is exported to the pdf SnapshotParameters snapshotParameters = new SnapshotParameters(); snapshotParameters.setTransform(new Scale(2, 2)); for (Chart chart : charts) { chartImages.add(chart.snapshot(snapshotParameters, null)); } return chartImages; }
@FXML private void handleFileSaveAction(ActionEvent event) { FileChooser fileChooser = new FileChooser(); File file = fileChooser.showSaveDialog(null); if (file != null) { try { WritableImage writableImage = new WritableImage((int) drawingCanvas.getWidth(), (int) drawingCanvas.getHeight()); drawingCanvas.snapshot(null, writableImage); RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null); ImageIO.write(renderedImage, "png", file); } catch (IOException ex) { Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex); } } }
@FXML private void handleFileSaveAction(ActionEvent event) { FileChooser fileChooser = new FileChooser(); File file = fileChooser.showSaveDialog(null); System.out.println("Saving #" + file + "#"); if (file != null) { // Stole the following part from: // http://java-buddy.blogspot.com/2013/04/save-canvas-to-png-file.html try { WritableImage writableImage = new WritableImage((int) drawingCanvas.getWidth(), (int) drawingCanvas.getHeight()); drawingCanvas.snapshot(null, writableImage); RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null); // hometask: make sure you can save files in any format (not just png) // hints: find the extension of the file from the filename, then use substring ImageIO.write(renderedImage, "png", file); } catch (IOException ex) { System.err.println("Couldn't save the file!"); // hometask: throw an alert dialog from here } } }
private void updatePlaceholder(Node newView) { if (view.getWidth() > 0 && view.getHeight() > 0) { SnapshotParameters parameters = new SnapshotParameters(); parameters.setFill(Color.TRANSPARENT); Image placeholderImage = view.snapshot(parameters, new WritableImage((int) view.getWidth(), (int) view.getHeight())); placeholder.setImage(placeholderImage); placeholder.setFitWidth(placeholderImage.getWidth()); placeholder.setFitHeight(placeholderImage.getHeight()); } else { placeholder.setImage(null); } placeholder.setVisible(true); placeholder.setOpacity(1.0); view.getChildren().setAll(placeholder, newView); placeholder.toFront(); }
public static boolean saveSnapshot(QuPathViewer viewer, File file) { ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); javafx.scene.canvas.Canvas canvas = viewer.getCanvas(); WritableImage image = new WritableImage((int)canvas.getWidth(), (int)canvas.getHeight()); image = canvas.snapshot(new SnapshotParameters(), image); try { ImageIO.write(SwingFXUtils.fromFXImage(image, null ), "png", byteOutput); FileOutputStream fileOutputStream = new FileOutputStream(file); fileOutputStream.write(byteOutput.toByteArray()); fileOutputStream.close(); byteOutput.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
private void updateHeatMap() { monochromeCanvas.snapshot(SNAPSHOT_PARAMETERS, monochromeImage); heatMap = new WritableImage(monochromeImage.widthProperty().intValue(), monochromeImage.heightProperty().intValue()); PixelWriter pixelWriter = heatMap.getPixelWriter(); PixelReader pixelReader = monochromeImage.getPixelReader(); Color colorFromMonoChromeImage; double brightness; Color mappedColor; for (int y = 0 ; y < monochromeImage.getHeight() ; y++) { for (int x = 0 ; x < monochromeImage.getWidth(); x++) { colorFromMonoChromeImage = pixelReader.getColor(x, y); //brightness = computeLuminance(colorFromMonoChromeImage.getRed(), colorFromMonoChromeImage.getGreen(), colorFromMonoChromeImage.getBlue()); //brightness = computeBrightness(colorFromMonoChromeImage.getRed(), colorFromMonoChromeImage.getGreen(), colorFromMonoChromeImage.getBlue()); brightness = computeBrightnessFast(colorFromMonoChromeImage.getRed(), colorFromMonoChromeImage.getGreen(), colorFromMonoChromeImage.getBlue()); mappedColor = getColorAt(mappingGradient, brightness); if (fadeColors) { //pixelWriter.setColor(x, y, Color.color(mappedColor.getRed(), mappedColor.getGreen(), mappedColor.getBlue(), brightness)); pixelWriter.setColor(x, y, Color.color(mappedColor.getRed(), mappedColor.getGreen(), mappedColor.getBlue(), colorFromMonoChromeImage.getOpacity())); } else { pixelWriter.setColor(x, y, mappedColor); } } } heatMapView.setImage(heatMap); }
public HeatMap(final double WIDTH, final double HEIGHT, ColorMapping COLOR_MAPPING, final double EVENT_RADIUS, final boolean FADE_COLORS, final double HEAT_MAP_OPACITY, final OpacityDistribution OPACITY_DISTRIBUTION) { super(); SNAPSHOT_PARAMETERS.setFill(Color.TRANSPARENT); eventList = new ArrayList(); eventImages = new HashMap<>(); colorMapping = COLOR_MAPPING; mappingGradient = colorMapping.mapping; fadeColors = FADE_COLORS; radius = EVENT_RADIUS; opacityDistribution = OPACITY_DISTRIBUTION; eventImage = createEventImage(radius, opacityDistribution); monochrome = new Canvas(WIDTH, HEIGHT); ctx = monochrome.getGraphicsContext2D(); monochromeImage = new WritableImage((int) WIDTH, (int) HEIGHT); setImage(heatMap); setMouseTransparent(true); setOpacity(HEAT_MAP_OPACITY); registerListeners(); }
/** * Recreates the heatmap based on the current monochrome map. * Using this approach makes it easy to change the used color * mapping. */ private void updateHeatMap() { monochrome.snapshot(SNAPSHOT_PARAMETERS, monochromeImage); heatMap = new WritableImage(monochromeImage.widthProperty().intValue(), monochromeImage.heightProperty().intValue()); Color colorFromMonoChromeImage; double brightness; Color mappedColor; PixelWriter pixelWriter = heatMap.getPixelWriter(); PixelReader pixelReader = monochromeImage.getPixelReader(); int width = (int) monochromeImage.getWidth(); int height = (int) monochromeImage.getHeight(); for (int y = 0 ; y < height ; y++) { for (int x = 0 ; x < width ; x++) { colorFromMonoChromeImage = pixelReader.getColor(x, y); brightness = colorFromMonoChromeImage.getOpacity(); mappedColor = getColorAt(mappingGradient, brightness); pixelWriter.setColor(x, y, fadeColors ? Color.color(mappedColor.getRed(), mappedColor.getGreen(), mappedColor.getBlue(), brightness) : mappedColor); } } setImage(heatMap); }
public HeatMap(final double WIDTH, final double HEIGHT, ColorMapping COLOR_MAPPING, final double SPOT_RADIUS, final boolean FADE_COLORS, final double HEAT_MAP_OPACITY, final OpacityDistribution OPACITY_DISTRIBUTION) { super(); SNAPSHOT_PARAMETERS.setFill(Color.TRANSPARENT); spotList = new ArrayList<>(); spotImages = new HashMap<>(); colorMapping = COLOR_MAPPING; mappingGradient = colorMapping.getGradient(); fadeColors = FADE_COLORS; radius = SPOT_RADIUS; opacityDistribution = OPACITY_DISTRIBUTION; spotImage = createSpotImage(radius, opacityDistribution); monochrome = new Canvas(WIDTH, HEIGHT); ctx = monochrome.getGraphicsContext2D(); monochromeImage = new WritableImage((int) WIDTH, (int) HEIGHT); setImage(heatMap); setMouseTransparent(true); setOpacity(HEAT_MAP_OPACITY); registerListeners(); }
/** * Recreates the heatmap based on the current monochrome map. * Using this approach makes it easy to change the used color * mapping. */ private void updateHeatMap() { monochrome.snapshot(SNAPSHOT_PARAMETERS, monochromeImage); int width = monochromeImage.widthProperty().intValue(); int height = monochromeImage.heightProperty().intValue(); heatMap = new WritableImage(width, height); Color colorFromMonoChromeImage; double brightness; Color mappedColor; PixelWriter pixelWriter = heatMap.getPixelWriter(); PixelReader pixelReader = monochromeImage.getPixelReader(); for (int y = 0 ; y < height ; y++) { for (int x = 0 ; x < width ; x++) { colorFromMonoChromeImage = pixelReader.getColor(x, y); brightness = colorFromMonoChromeImage.getOpacity(); mappedColor = Helper.getColorAt(mappingGradient, brightness); pixelWriter.setColor(x, y, fadeColors ? Color.color(mappedColor.getRed(), mappedColor.getGreen(), mappedColor.getBlue(), brightness) : mappedColor); } } setImage(heatMap); }
@Override @FXThread protected boolean validate(@NotNull final VarTable vars) { final Color color = UIUtils.from(vars.get(PROP_COLOR, ColorRGBA.class)); final int width = vars.getInteger(PROP_WIDTH); final int height = vars.getInteger(PROP_HEIGHT); final WritableImage writableImage = new WritableImage(width, height); final PixelWriter pixelWriter = writableImage.getPixelWriter(); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { pixelWriter.setColor(i, j, color); } } getImageView().setImage(writableImage); return true; }
@Override @BackgroundThread protected void writeData(@NotNull final VarTable vars, final @NotNull Path resultFile) throws IOException { super.writeData(vars, resultFile); final Color color = UIUtils.from(vars.get(PROP_COLOR, ColorRGBA.class)); final int width = vars.getInteger(PROP_WIDTH); final int height = vars.getInteger(PROP_HEIGHT); final WritableImage writableImage = new WritableImage(width, height); final PixelWriter pixelWriter = writableImage.getPixelWriter(); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { pixelWriter.setColor(i, j, color); } } final BufferedImage bufferedImage = SwingFXUtils.fromFXImage(writableImage, null); try (final OutputStream out = Files.newOutputStream(resultFile)) { ImageIO.write(bufferedImage, "png", out); } }
/** * Generates a panel image form char. * <p>First, this function converts ch to upper case if ch is lower case.</p> * <p>Then, this generates javafx's image from ch.And return it.</p> * You can fix the resolution of image through {@link capslock.CharPanelGenerator#PANEL_IMAGE_SIZE} * and {@link capslock.CharPanelGenerator#FONT_SIZE}. * @param ch パネルの生成に使う1文字. * @param color 背景色. * @return 生成されたパネル. */ static final Image generate(char ch, Color color){ final Label label = new Label(Character.toString(Character.toUpperCase(ch))); label.setMinSize(PANEL_IMAGE_SIZE, PANEL_IMAGE_SIZE); label.setMaxSize(PANEL_IMAGE_SIZE, PANEL_IMAGE_SIZE); label.setPrefSize(PANEL_IMAGE_SIZE, PANEL_IMAGE_SIZE); label.setFont(Font.font(FONT_SIZE)); label.setAlignment(Pos.CENTER); label.setTextFill(Color.WHITE); label.setBackground(new Background(new BackgroundFill(color, CornerRadii.EMPTY, Insets.EMPTY))); final Scene scene = new Scene(new Group(label)); final WritableImage img = new WritableImage(PANEL_IMAGE_SIZE, PANEL_IMAGE_SIZE); scene.snapshot(img); return img ; }
/** * 把一个Node导出为png图片 * * @param node 节点 * @param saveFile 图片文件 * @param width 宽 * @param height 高 * @return 是否导出成功 */ public static boolean node2Png(Node node, File saveFile, double width, double height) { SnapshotParameters parameters = new SnapshotParameters(); // 背景透明 parameters.setFill(Color.TRANSPARENT); WritableImage image = node.snapshot(parameters, null); // 重置图片大小 ImageView imageView = new ImageView(image); imageView.setFitWidth(width); imageView.setFitHeight(height); WritableImage exportImage = imageView.snapshot(parameters, null); try { return ImageIO.write(SwingFXUtils.fromFXImage(exportImage, null), "png", saveFile); } catch (IOException e) { e.printStackTrace(); } return false; }
/** * Take a screenshot of a scene and write it as a .png file */ @Override public void createSceneScreenshotPNG(Scene screenshotZone, String imageName) { WritableImage screenshot = screenshotZone.snapshot(null); // TODO where to save? File file = new File( VoogaBundles.imageProperties.getString("saveLocation") + imageName + VoogaBundles.imageProperties.getString(DOT_PNG)); try { ImageIO.write(SwingFXUtils.fromFXImage(screenshot, null), VoogaBundles.imageProperties.getString(PNG), file); } catch (IOException e) { VoogaAlert alert = new VoogaAlert(VoogaBundles.exceptionProperties.getString("SnapshotFail")); alert.showAndWait(); } }
public static Image x32Tox64(Image srcSkin) { if (srcSkin.getHeight() == 64) return srcSkin; WritableImage newSkin = new WritableImage((int) srcSkin.getWidth(), (int) srcSkin.getHeight() * 2); PixelCopyer copyer = new PixelCopyer(srcSkin, newSkin); // HEAD & HAT copyer.copy(0 / 64F, 0 / 32F, 0 / 64F, 0 / 64F, 64 / 64F, 16 / 32F); // LEFT-LEG x32Tox64(copyer, 0 / 64F, 16 / 32F, 16 / 64F, 48 / 64F, 4 / 64F, 12 / 32F, 4 / 64F); // RIGHT-LEG copyer.copy(0 / 64F, 16 / 32F, 0 / 64F, 16 / 64F, 16 / 64F, 16 / 32F); // BODY copyer.copy(16 / 64F, 16 / 32F, 16 / 64F, 16 / 64F, 24 / 64F, 16 / 32F); // LEFT-ARM x32Tox64(copyer, 40 / 64F, 16 / 32F, 32 / 64F, 48 / 64F, 4 / 64F, 12 / 32F, 4 / 64F); // RIGHT-ARM copyer.copy(40 / 64F, 16 / 32F, 40 / 64F, 16 / 64F, 16 / 64F, 16 / 32F); return newSkin; }
@Override public void handle(final MouseEvent event) { final Pane pane = (Pane) event.getSource(); final ImageView view = (ImageView) pane.getChildren().get(0); final Dragboard db = view.startDragAndDrop(TransferMode.COPY); final ClipboardContent content = new ClipboardContent(); content.putString(view.getId()); final ComponentPane componentPane = loadComponent(pane.getChildren().get(0).getId().toLowerCase()); workspace.getChildren().add(componentPane); componentPane.applyCss(); final WritableImage w = componentPane.snapshot(null,null); workspace.getChildren().remove(componentPane); content.putImage(w); db.setContent(content); event.consume(); }
@Override protected Image getImage() { WritableImage image = new WritableImage(256, 256); byte[] imageInArray = new byte[256 * 256 * 4]; //Create byte image array for (int i = 0; i < 256; i++) { for (int j = 0; j < 256; j++) { int color = i + j; int intValue = getColorComponentProvider().getARGBColor( ((color > 255) ? 255 : color)); for (int k = 0; k < 4; k++) { imageInArray[i * 4 + j * 256 * 4 + k] = (byte)((intValue >>> (k * 8)) & (0x000000FF)); } } } //Copy bytes to image image.getPixelWriter().setPixels(0, 0, 256, 256, PixelFormat.getByteBgraInstance(), imageInArray, 0, 256 * 4); return image; }
@Override protected Image getImage() { WritableImage image = new WritableImage(256, 256); int[] imageInArray = new int[256 * 256]; for (int i = 0; i < 256; i++) { for (int j = 0; j < 256; j++) { int color = i + j; imageInArray[i + j * 256] = getColorComponentProvider().getARGBColor( ((color > 255) ? 255 : color)); } } image.getPixelWriter().setPixels(0, 0, 256, 256, PixelFormat.getIntArgbInstance(), imageInArray, 0, 256); return image; }
@Override protected Image getImage() { WritableImage image = new WritableImage(256, 256); PixelWriter pixelWriter = image.getPixelWriter(); for (int i = 0; i < 256; i++) { for (int j = 0; j < 256; j++) { double color = i + j; pixelWriter.setColor(i, j, getColorComponentProvider().getColor( ((color > 255) ? 255.0 : color) / 255)); } } return image; }
@Override protected Image getImage() { WritableImage image = new WritableImage(256, 256); PixelWriter pixelWriter = image.getPixelWriter(); for (int i = 0; i < 256; i++) { for (int j = 0; j < 256; j++) { int color = i + j; pixelWriter.setArgb(i, j, getColorComponentProvider().getARGBColor( ((color > 255) ? 255 : color))); } } return image; }
public static Image createNoiseImage(final double WIDTH, final double HEIGHT, final Color DARK_COLOR, final Color BRIGHT_COLOR, final double ALPHA_VARIATION_IN_PERCENT) { if (Double.compare(WIDTH, 0) <= 0 || Double.compare(HEIGHT, 0) <= 0) return null; int width = (int) WIDTH; int height = (int) HEIGHT; double alphaVariationInPercent = Helper.clamp(0.0, 100.0, ALPHA_VARIATION_IN_PERCENT); final WritableImage IMAGE = new WritableImage(width, height); final PixelWriter PIXEL_WRITER = IMAGE.getPixelWriter(); final Random BW_RND = new Random(); final Random ALPHA_RND = new Random(); final double ALPHA_START = alphaVariationInPercent / 100 / 2; final double ALPHA_VARIATION = alphaVariationInPercent / 100; for (int y = 0 ; y < height ; y++) { for (int x = 0 ; x < width ; x++) { final Color NOISE_COLOR = BW_RND.nextBoolean() == true ? BRIGHT_COLOR : DARK_COLOR; final double NOISE_ALPHA = Helper.clamp(0.0, 1.0, ALPHA_START + ALPHA_RND.nextDouble() * ALPHA_VARIATION); PIXEL_WRITER.setColor(x, y, Color.color(NOISE_COLOR.getRed(), NOISE_COLOR.getGreen(), NOISE_COLOR.getBlue(), NOISE_ALPHA)); } } return IMAGE; }
public static Image get(String key, int tileX, int tileY) { if (!sheets.containsKey(key)) { throw new AssertionError("image does not exist"); } // try to get image from cache if (tiles.get(key)[tileX][tileY] != null) { return tiles.get(key)[tileX][tileY]; } // generate new image from sheet PixelReader reader = sheets.get(key).getPixelReader(); WritableImage newImage = new WritableImage(reader, (WIDTH + MARGIN) * tileX, (HEIGHT + MARGIN) * tileY, WIDTH, HEIGHT); // put new image in cache tiles.get(key)[tileX][tileY] = newImage; return newImage; }
/** * This method receives an image scales it * @param input Input image * @param scaleFactor Output scale factor * @return The resampled image */ public Image resampleImage(Image input, int scaleFactor) { int W = (int) input.getWidth(); int H = (int) input.getHeight(); WritableImage output = new WritableImage( W * scaleFactor, H * scaleFactor ); PixelReader reader = input.getPixelReader(); PixelWriter writer = output.getPixelWriter(); for (int y = 0; y < H; y++) { for (int x = 0; x < W; x++) { int argb = reader.getArgb(x, y); for (int dy = 0; dy < scaleFactor; dy++) { for (int dx = 0; dx < scaleFactor; dx++) { writer.setArgb(x * scaleFactor + dx, y * scaleFactor + dy, argb); } } } } return output; }
/** * Get an Image Instance for Use in JavaFX. * * @return javafx image */ public WritableImage getImage() { Settings s = new Settings(); java.awt.Color paper = fxToAWTColor(background); java.awt.Color ink = fxToAWTColor(foreground); BufferedImage image = new BufferedImage((barcode.getWidth() * zoom) + (2 * border), (barcode.getHeight() * zoom) + (2 * border), BufferedImage.TYPE_INT_RGB); Graphics2D g2d = image.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.fillRect(0, 0, (barcode.getWidth() * zoom) + (2 * border), (barcode.getHeight() * zoom) + (2 * border)); Java2DRenderer renderer = new Java2DRenderer(g2d, zoom, border, paper, ink); renderer.render(barcode); return SwingFXUtils.toFXImage(image, null); }
/** * Colorizes an image by the given amount * * @param img Image * @param c Color * @param a Double amount * @return Image */ public static Image colorizeImage(Image img, Color c, double a) { PixelReader reader = img.getPixelReader(); WritableImage write = new WritableImage((int) img.getWidth(), (int) img.getHeight()); PixelWriter writer = write.getPixelWriter(); for(int readY = 0; readY < img.getHeight(); readY++){ for(int readX = 0; readX < img.getWidth(); readX++) { Color color = reader.getColor(readX, readY); if(color.getOpacity() == 0) continue; color = color.interpolate(c, a); writer.setColor(readX, readY, color); } } return (Image) write; }
Image createImage(BigInteger startIndex, int count, long step) { int width = idxCount.subtract(BigInteger.ONE).bitLength(); WritableImage img = new WritableImage(2 * width, 2 * count); PixelWriter pw = img.getPixelWriter(); for (int y = 0 ; y < count ; y++) { BigInteger idx = startIndex.add(BigInteger.valueOf(y * step)); BigInteger shuffIdx = shuffler.getShuffledIndex(idx, idxCount); boolean[] shuffledBits = toBoolBits(shuffIdx, idxCount); for (int x = 0 ; x < width ; x++) { Color color = shuffledBits[x] ? Color.BLACK : Color.WHITE; pw.setColor(2 * x, 2 * y, color); pw.setColor(2 * x + 1, 2 * y, color); pw.setColor(2 * x, 2 * y + 1, color); pw.setColor(2 * x + 1, 2 * y + 1, color); } } return img; }
private void handleSaveImageButtonAction(ActionEvent event) { BufferedImage saveImage = mMenuTerrain.isSelected() ? mTerrainImage : mFantasyImage; FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(mSaveImageButton.getText()); fileChooser.setInitialDirectory(new File(System.getProperty("user.home"), "Pictures")); FileChooser.ExtensionFilter extensionFilter = new FileChooser.ExtensionFilter("PNG", "*.png"); fileChooser.getExtensionFilters().add(extensionFilter); File file = fileChooser.showSaveDialog(mStage); if (file != null) { try { WritableImage writableImage = new WritableImage(saveImage.getWidth(), saveImage.getHeight()); SwingFXUtils.toFXImage(saveImage, writableImage); ImageIO.write(SwingFXUtils.fromFXImage(writableImage, null), "png", file); } catch (IOException ioe) { Logger.getLogger(TAG).log(Level.SEVERE, null, ioe); } } }
/** * Get a scaled (RGB or ARGB) image, achieving reasonable quality even when scaling down by a considerably amount. * * Code is based on https://today.java.net/article/2007/03/30/perils-imagegetscaledinstance * * @param img * @param targetWidth * @param targetHeight * @return */ static WritableImage getScaledRGBInstance(BufferedImage img, int targetWidth, int targetHeight) { int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB; BufferedImage imgResult = (BufferedImage)img; int w = img.getWidth(); int h = img.getHeight(); while (w > targetWidth || h > targetHeight) { w = Math.max(w / 2, targetWidth); h = Math.max(h / 2, targetHeight); BufferedImage imgTemp = new BufferedImage(w, h, type); Graphics2D g2 = imgTemp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(imgResult, 0, 0, w, h, null); g2.dispose(); imgResult = imgTemp; } return SwingFXUtils.toFXImage(imgResult, null); }
public JfxRenderer(ImageView imageView, int width, int height, boolean depthBuffer) { this.imageView = imageView; this.width = width; this.height = height; this.byteBuffer = BufferUtils.createByteBuffer(width * height * 4); this.scanlineStride = width * 4; this.renderImage = new WritableImage(width, height); this.imageView.setImage(renderImage); if (depthBuffer) { frameBuffer = new FrameBuffer(width, height, 1); frameBuffer.setDepthBuffer(Format.Depth); frameBuffer.setColorBuffer(Format.BGRA8); } else { frameBuffer = null; } }
public PreviewComponent(Region n) { SnapshotParameters snp = new SnapshotParameters(); WritableImage image = n.snapshot(snp,null); Group g = new Group(); g.getChildren().add(new ImageView(image)); Scene newScene = new Scene(g, n.getWidth(),n.getHeight()); g.getChildren().add(n); this.initStyle(StageStyle.UNDECORATED); this.setScene(newScene); this.setOpacity(0.5); this.show(); }
@Override public WritableImage export(int width, int height) { VBox root = new VBox(); root.setStyle("-fx-background-color: transparent;"); root.setPadding(new Insets(25)); root.getChildren().add(generate(false)); Stage newStage = new Stage(); newStage.initModality(Modality.NONE); newStage.setScene(new Scene(root, width, height)); newStage.setResizable(false); newStage.show(); SnapshotParameters sp = new SnapshotParameters(); sp.setTransform(Transform.scale(width / root.getWidth(), height / root.getHeight())); newStage.close(); return root.snapshot(sp, null); }
@Override public void write(final ReportSummaryWriter writer) { // Snapshots must be taken on the application thread, so tell the application thread to take care of this when it has a chance... final Task<WritableImage> getImageSnapshotTask = new Task<WritableImage>() { @Override protected WritableImage call() throws Exception { new Scene(HeatMapSummaryComponent.this.chart, -1, -1); return HeatMapSummaryComponent.this.chart.snapshot(new SnapshotParameters(), null); } }; Platform.runLater(getImageSnapshotTask); // Wait for the application thread to do it's stuff, then write the image try { final WritableImage image = getImageSnapshotTask.get(); writer.writeImage(SwingFXUtils.fromFXImage(image, null)); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } }
public void renderPath(Path2D p2d, Path p, WritableImage wimg) { if (useJava2D) { BufferedImage bimg = new BufferedImage(TESTW, TESTH, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = bimg.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); g2d.setColor(java.awt.Color.WHITE); g2d.fillRect(0, 0, TESTW, TESTH); g2d.setColor(java.awt.Color.BLACK); if (useJava2DClip) { g2d.setClip(p2d); g2d.fillRect(0, 0, TESTW, TESTH); g2d.setClip(null); } else { g2d.fill(p2d); } copy(bimg, wimg); } else { setPath(p, p2d); SnapshotParameters sp = new SnapshotParameters(); sp.setViewport(new Rectangle2D(0, 0, TESTW, TESTH)); p.snapshot(sp, wimg); } }
public void update(Path2D p2d) { setPath(resultpath, p2d); Path p = makePath(); WritableImage wimg = new WritableImage(TESTW, TESTH); renderPath(p2d, p, wimg); PixelReader pr = wimg.getPixelReader(); GraphicsContext gc = resultcv.getGraphicsContext2D(); gc.save(); for (int y = 0; y < TESTH; y++) { for (int x = 0; x < TESTW; x++) { boolean inpath = p2d.contains(x + 0.5, y + 0.5); boolean nearpath = near(p2d, x + 0.5, y + 0.5, warn); int pixel = pr.getArgb(x, y); renderPixelStatus(gc, x, y, pixel, inpath, nearpath); } } gc.restore(); }
private void saveSnapshot() { WritableImage snapImg = root.snapshot(null, null); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Save SnapShot"); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png")); fileChooser.setInitialDirectory(new File(globalPrefs.getMostRecentSaveFolder())); fileChooser.setInitialFileName(String.format("binjr_snapshot_%s.png", getWorksheet().getName())); File selectedFile = fileChooser.showSaveDialog(Dialogs.getStage(root)); if (selectedFile != null) { try { if (selectedFile.getParent() != null) { globalPrefs.setMostRecentSaveFolder(selectedFile.getParent()); } ImageIO.write( SwingFXUtils.fromFXImage(snapImg, null), "png", selectedFile); } catch (IOException e) { Dialogs.notifyException("Failed to save snapshot to disk", e, root); } } }