9

I have an SVG image created in Inkscape. I put it in the same directory as my class.

Is there a way to load that image and convert it to an SVG Path?

The idea behind this is to get that image with getClass().getResource("image.svg").toExternalForm() and convert it to a SVGPath for the imageSVG.setContent() method. After of that I want to put that SVGPath object in a Button with the button.setGraphic() method.

I don't want to use Transcoders or BufferedImage class.

Robert Longson
  • 118,664
  • 26
  • 252
  • 242
Deus Arcana
  • 93
  • 1
  • 1
  • 7
  • 1
    Possible duplicate of [SVG Image in JavaFX 2.2](http://stackoverflow.com/questions/12436274/svg-image-in-javafx-2-2) – SSchuette Oct 17 '16 at 05:49
  • You should have a look at the __working solution__ at http://stackoverflow.com/questions/12436274/svg-image-in-javafx-2-2/23894292#23894292 – SSchuette Oct 17 '16 at 05:50
  • 1
    You could use the SVG loader which I implemented: it reads an `.svg` file and returns a hierarchy of corresponding JavaFX nodes: https://github.com/afester/FranzXaver See the examples at https://github.com/afester/FranzXaver/tree/master/Example. s/src/main/java/afester/javafx/examples/svg. I was especially using InkScape to verify the `.svg` format – Andreas Fester Oct 17 '16 at 06:57

1 Answers1

12

With the SvgLoader provided by https://github.com/afester/FranzXaver, you can simply load an SVG file as a JavaFX node and set it on the button as its graphic:

...
    // load the svg file
    InputStream svgFile = 
          getClass().getResourceAsStream("/afester/javafx/examples/data/Ghostscript_Tiger.svg");
    SvgLoader loader = new SvgLoader();
    Group svgImage = loader.loadSvg(svgFile);

    // Scale the image and wrap it in a Group to make the button 
    // properly scale to the size of the image  
    svgImage.setScaleX(0.1);
    svgImage.setScaleY(0.1);
    Group graphic = new Group(svgImage);

    // create a button and set the graphics node
    Button button = new Button();
    button.setGraphic(graphic);

    // add the button to the scene and show the scene
    HBox layout = new HBox(button);
    HBox.setMargin(button, new Insets(10));
    Scene scene = new Scene(layout);
    primaryStage.setScene(scene);
    primaryStage.show();
...

Screenshot of image on button

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
  • You could use the [Node.snapshot()](https://docs.oracle.com/javase/10/docs/api/javafx/scene/Node.html#snapshot(javafx.scene.SnapshotParameters,javafx.scene.image.WritableImage)) method to render the `Group` into an image, and then use this `Image` in your `ImageView`. You would however loose the benefit to freely scale the graphic ... – Andreas Fester Mar 26 '18 at 09:21