使用Java捕获和显示图像 [英] Capturing and displaying an image using Java

查看:125
本文介绍了使用Java捕获和显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次用Java编写代码,所以请跟我一起玩。 :P

我想创建一个捕获屏幕(1280x720 res)然后显示它的应用程序。这个代码是在一个while循环中,所以它正在进行中。这就是我所拥有的:

This is my first time coding in Java, so please bare with me. :P
I want to create an app which captures the screen (1280x720 res) and then displays it. The code for this is in a while loop so it's ongoing. Here's what I've got:

import javax.swing.*;

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;

public class SV1 {

    public static void main(String[] args) throws Exception {
        JFrame theGUI = new JFrame();
        theGUI.setTitle("TestApp");
        theGUI.setSize(1280, 720);
        theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        theGUI.setVisible(true);

        Robot robot = new Robot();

        while (true) {
            BufferedImage screenShot = robot.createScreenCapture(new Rectangle(1280,720));

            JLabel picLabel = new JLabel(new ImageIcon( screenShot ));
            theGUI.add(picLabel);
        }
    }
}

我从< a href =https://stackoverflow.com/a/2706730/303221>这个答案但它并不适合我想要的东西。首先,由于某些原因我不确定,它会导致java耗尽内存Java堆空间。其次它不能正常工作,因为显示的图像没有更新。

I figured this out from this answer but it isn't ideal for what I want. First of all, for some reason I'm not sure of, it causes java to run out of memory "Java heap space". And secondly it doesn't work properly as the image shown isn't updated.

我读过有关使用Graphics(java.awt.Graphics)绘制图像的内容。有人能告诉我这个例子吗?或者,如果有更好的方法,或许让我指向正确的方向?谢谢您的帮助。 :)

I've read about using Graphics (java.awt.Graphics) to draw the image. Can anyone show me an example of this? Or perhaps point me in the right direction if there's a better way? Thanks for the help. :)

推荐答案


它导致java内存不足Java堆空间

it causes java to run out of memory "Java heap space"

您正在永久循环并不断向您的 JFrame 添加新的JLabel。
您可以尝试而不是每次重新创建JLabel,只需设置一个新的ImageIcon:

You are looping forever and continuosly adding new JLabels to your JFrame. You could try instead of recreating each time the JLabel, to simply set a new ImageIcon:

JLabel picLabel = new JLabel();
theGUI.add(picLabel);
while (true) 
{
    BufferedImage screenShot = robot.createScreenCapture(new Rectangle(1280,720));
    picLabel.setIcon(new ImageIcon(screenShot));   

}

如果你想用画画图形(在这种情况下它可能是一个更好的主意),你可以扩展 JLabel 并覆盖 paintComponent 方法,在其中绘制图像:

If you want to paint using Graphics(in this case it's probably a better idea), you can extend a JLabel and override paintComponent method, drawing the image inside it:

public class ScreenShotPanel extends JLabel
{

    @override
    public void paintComponent(Graphics g) {
        BufferedImage screenShot = robot.createScreenCapture(new Rectangle(1280,720));
        g.drawImage(screenShot,0,0,this);
    }
}

这篇关于使用Java捕获和显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆