如何将滚动窗格内容保存为 jpg 文件

Posted

技术标签:

【中文标题】如何将滚动窗格内容保存为 jpg 文件【英文标题】:how to save scrollpane content as a jpg file 【发布时间】:2017-04-12 19:29:43 【问题描述】:

下面是我的代码,我试图将ScrollPane 内容保存为 jpg 文件。它给了我一个IllegalArgumentException 错误。到目前为止,我已经尝试过使用this 和this,但显然我在ImageIO.write 方法中输入了错误的参数。我在这里错过了什么?

    package urd.View;

    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.util.logging.Level; 
    import java.util.logging.Logger;
    import javafx.application.Application;
    import static javafx.application.Application.launch;
    import javafx.embed.swing.SwingFXUtils;
    import javafx.event.ActionEvent; 
    import javafx.scene.Scene;
    import javafx.scene.SnapshotParameters;
    import javafx.scene.control.Menu;
    import javafx.scene.control.MenuBar;
    import javafx.scene.control.MenuItem;
    import javafx.scene.control.ScrollPane;
    import javafx.scene.image.WritableImage;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.layout.Pane; 
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Circle;
    import javafx.scene.shape.Rectangle;
    import javafx.stage.Stage;
    import javax.imageio.ImageIO;
    import javax.swing.JFileChooser;

    /**
    *
    * @author urd
    */
    public class NewFXMain extends Application 

private final int width = 250;
private final int height = 250;

private final int radius = 15;
double circleX = width / 2;
double circleY = height / 2;
Circle circle = new Circle(circleX, circleY, radius);

/**
 * @param args the command line arguments
 */
public static void main(String[] args) 
    launch(args);


/**
 * @param primaryStage the command line arguments
 */
@Override
public void start(Stage primaryStage) 
    BorderPane rootPane = new BorderPane();
    ScrollPane scrollPane = new ScrollPane();
    MenuBar menuBar = new MenuBar();
    Menu fileMenu = new Menu("File");
    Menu generator = new Menu("generate");
    MenuItem generateItem = new MenuItem("generate");
    menuBar.getMenus().addAll(fileMenu, generator);
    MenuItem saveItem = new MenuItem("Save Image");
    fileMenu.getItems().addAll(saveItem);
    generator.getItems().addAll(generateItem);
    rootPane.setTop(menuBar);
    rootPane.setCenter(scrollPane);
    Scene scene = new Scene(rootPane, 400, 350);
    primaryStage.setTitle("Image Generator");
    primaryStage.setScene(scene);
    primaryStage.show();
    saveItem.setOnAction((ActionEvent event) -> 
        // the content of scrollPane is saved as a JPEG file.
        WritableImage img = scrollPane.snapshot(new SnapshotParameters(), null);
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File(System.getProperty("user.home")));
        File fileToSave = chooser.getSelectedFile();
        BufferedImage img2 = SwingFXUtils.fromFXImage(img, null);
        int result = chooser.showSaveDialog(null);
        if (result == JFileChooser.APPROVE_OPTION) 
            try 
                ImageIO.write(img2, "png", fileToSave);
             catch (IOException ex) 
                Logger.getLogger(GuiClass.class.getName()).log(Level.SEVERE, null, ex);
            
        
    );
    generateItem.setOnAction((ActionEvent event) -> 
        //Here we call the generateImage method which takes in two int values and returns a pane
        scrollPane.setContent(generateImage());
    );


private Pane generateImage() 
    Rectangle rectCanvas = new Rectangle(width,
        height);
    rectCanvas.setFill(Color.GREEN);
    circle.setFill(Color.RED);
    Pane pane = new Pane();
    pane.getChildren().addAll(rectCanvas, circle);
    return pane;

这是IllegalArgumentException的日志

    Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: output == null!
at javax.imageio.ImageIO.write(ImageIO.java:1516)
at urd.View.NewFXMain.lambda$start$0(NewFXMain.java:86)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.control.MenuItem.fire(MenuItem.java:462)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.doSelect(ContextMenuContent.java:1405)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.lambda$createChildren$343(ContextMenuContent.java:1358)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)

【问题讨论】:

我看到您已经有一个批准的答案,但您确定要在看起来像 JavaFX 的应用程序中使用 Swing JFileChooser 好吧,给定的答案确实解决了我的问题。但作为一个编程新手,我什至不知道 javaFX 应用程序中的 swing 组件可能有问题。你能建议用于教育目的的链接吗?我将不胜感激!谢谢 【参考方案1】:

chooser.getSelectedFile() 在调用 showSaveDialog() 后返回 File 对象,因此在调用 showSaveDialog() 方法后创建文件对象。

    saveItem.setOnAction((ActionEvent event) -> 
                // the content of scrollPane is saved as a JPEG file.
                WritableImage img = scrollPane.snapshot(new SnapshotParameters(), null);
                JFileChooser chooser = new JFileChooser();
                chooser.setCurrentDirectory(new File(System.getProperty("user.home")));
               // File fileToSave = chooser.getSelectedFile();//Remove this line.
                BufferedImage img2 = SwingFXUtils.fromFXImage(img, null);
                int result = chooser.showSaveDialog(null);
                if (result == JFileChooser.APPROVE_OPTION) 
                    try 
                        File fileToSave = chooser.getSelectedFile();
                        ImageIO.write(img2, "png", fileToSave);
                     catch (IOException ex) 
                        Logger.getLogger(GuiClass.class.getName()).log(Level.SEVERE, null, ex);
                    
                
            );

【讨论】:

这么简单...谢谢!

以上是关于如何将滚动窗格内容保存为 jpg 文件的主要内容,如果未能解决你的问题,请参考以下文章

如何在 react-split-pane 中分别支持单个窗格的滚动?

拆分窗格、滚动窗格和布局如何工作

html设置滚动内容

如何使用类似于 chart.io 和 simple.com 的平滑滚动窗格创建动画菜单

如何始终滚动到文本区域的底部?

为画布设置滚动窗格的问题