【问题标题】:Convert a region of a JPanel into a BufferedImage将 JPanel 的区域转换为 BufferedImage
【发布时间】:2010-01-14 18:13:32
【问题描述】:

我需要将 jpanel 的某个区域转换为 bufferedImage,或其他格式以显示在另一个 jpanel 中。

到目前为止,我只看到了将整个 jpanel 转换为 bufferedImage 的代码,但就我而言,我只需要 jpanel 内的一个区域。

谢谢

【问题讨论】:

    标签: java swing jpanel


    【解决方案1】:

    创建一个具有请求大小的 BufferedImage 以接收图像。
    获取一个用于在此图像上绘图的 Graphics2D,并让 JPanel 在其上绘图。

        JPanel panel = ...
        BufferedImage image = new BufferedImage(200, 200, TYPE_INT_ARGB);
        Graphics2D gg = image.createGraphics();
        try {
            gg.translate(-100, -20);  // start point of region negated
            panel.paint(gg);
        } finally {
            gg.dispose();
        }
    

    【讨论】:

    • 你可能会发现你需要使用 printAll(Graphics) 而不是 paint(Graphics)。我认为这是此类事情的推荐方法。
    【解决方案2】:

    由于您已经拥有将整个事物转换为 BufferedImage 的代码,因此您可以使用该代码,然后在生成的 BufferedImage 上调用 getSubImage 以获取子区域。

    【讨论】:

      【解决方案3】:

      到目前为止,我只看到了将整个 jpanel 转换为 bufferedImage 的代码,但就我而言,我只需要 jpanel 内的一个区域。

      然后拍摄该图像并将所需区域重新绘制为新图像,然后您就完成了。

      【讨论】:

      • 奥斯卡——你的声望都花在哪里了??赏金? ^^
      • 每次达到10K我就重生了:)
      【解决方案4】:

      最简单的可能是Robot.createScreenCapture()

      您需要将面板坐标系转换为屏幕坐标系。请参阅Component.getBounds()Component.getLocationOnScreen()

      【讨论】:

      • 您引用的链接似乎是本地链接,您可能需要更新该链接,以免有人因无辜错误而对您投反对票。
      猜你喜欢
      • 2020-11-01
      • 2014-01-07
      • 2013-08-10
      • 2013-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多