Search code examples
javajavafxphoto-gallery

Adding frame to picture in Javafx


i would like to add a frame to a picture using Java and Javafx and then save the framed picture. What would be the best way to do that?

For example say I have a photo of a landscape and want to add a frame to it. The framed photo should look like this: saved image


Solution

  • You could add two images, first the frame, then the image, to the same canvas like this:

    GraphicsContext gc1 = canvas.getGraphicsContext2D();
    gc1.drawImage(frameimage,0,0,image.getFitWidth()+20,image.getFitHeight()+20);
    GraphicsContext gc = canvas.getGraphicsContext2D();
    gc.drawImage(i,10,10,image.getFitWidth(),image.getFitHeight());
    

    and then save them as png (or whatever format you like) using the canvas.snapshot function:

    FileChooser fileChooser = new FileChooser();
    FileChooser.ExtensionFilter extFilter =new FileChooser.ExtensionFilter("png files (*.png)", "*.png");
    
    fileChooser.getExtensionFilters().add(extFilter);
    Stage primaryStage = (Stage) canvas.getScene().getWindow();
    
    File file = fileChooser.showSaveDialog(primaryStage);
    if(file != null){
            try {
                WritableImage writableImage = new WritableImage((int)canvas.getWidth(), (int)canvas.getHeight());
                canvas.snapshot(null, writableImage);
                RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
                File file1 = new File(file.getAbsolutePath()+".png");
    
                file.renameTo(file1);
    
                ImageIO.write(renderedImage, "png", file1);
    
    
            } catch (IOException ex) {
                ex.printStackTrace();
    }