【问题标题】:BufferedImage performance缓冲图像性能
【发布时间】:2013-12-25 23:04:41
【问题描述】:

我正在查看来自 ludumdale(minicraft) 的 Notch 的代码,我注意到他使用了:

private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();

所以我做了一个简单的测试程序,我注意到与我之前使用的方法相比,我的性能下降了很多。使用这种方法,只需绘制一个全白的屏幕,我就可以得到 800 fps,而当我绘制测试图像时,我会得到 1200 以上,这似乎有点奇怪。即使我没有在pixels[] 上声明任何内容,只保留默认值,它仍然是 800 fps。我想知道是否有人可以解释我这样做的原因。这是我编写的测试代码,我使用 fraps 来获取我的 fps:

public class Test extends Canvas implements Runnable{

private static final long serialVersionUID = 1L;

private boolean running = false;

public  final int HEIGHT = 300;
public  final int WIDTH = 360;
private final int SCALE = 3;

private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
private BufferedImage testImage;
private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();

JFrame frame;
public Test(){
    Dimension size = new Dimension(WIDTH*SCALE, HEIGHT*SCALE);
    frame = new JFrame();
    this.frame.setResizable(false);
    this.setPreferredSize(size);
    this.setMaximumSize(size);
    this.setMinimumSize(size);
    this.frame.add(this);
    this.frame.pack();
    this.frame.setLocationRelativeTo(null);
    this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setFocusable(true);
    this.frame.setVisible(true);

    try {
        testImage = ImageIO.read(new File("res/test.jpg"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    for(int i = 0; i < pixels.length; i++){
    pixels[i] = 0xffffff;
    }
    running = true;
}

public void run() {
    while(running){
        render();
    }
}

private void render() {
    BufferStrategy bs = getBufferStrategy();
    if(bs == null){
        createBufferStrategy(3);
        return;
    }

    Graphics g = bs.getDrawGraphics();
    //Draw stuff
    g.setColor(Color.BLACK);
    g.fillRect(0, 0, getWidth(), getHeight());
    g.drawImage(testImage, 0, 0, getWidth(), getHeight(), null);
    g.dispose();
    bs.show();
}

public static void main(String args[]){
    Test test = new Test();
    test.run();
}

}

我只是将testImage 替换为image。谢谢大家,节日快乐

编辑:我注意到只需调用 int[] pixel = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();大大降低了应用程序的速度。有人可以解释一下为什么会这样吗?我需要处理像素还是什么?谢谢

【问题讨论】:

    标签: java graphics jframe bufferedimage


    【解决方案1】:

    据我所知,BufferedImages 在幕后被视为 VolatileImages。这意味着他们获得了巨大的硬件加速提升。这是因为图像会直接复制到您的视频卡的内存中,从而实现快速绘图。

    在您想要访问像素矩阵的那一刻,图像将被放置在您的常规 RAM 中,并从那里访问,因此会导致显着变慢。

    实际上,如果您在 JVM 中禁用所有硬件加速,则白色图像的绘制速度最快。

    如果您想有效地更新屏幕,请将 setIgnoreRepaint(true) 应用于您的窗口,并且只绘制已更改的屏幕部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      • 2013-08-07
      • 1970-01-01
      • 2016-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多