Home > other >  Why set pixels images very slow
Why set pixels images very slow

Time:07-31

I am trying to render an image where I can manipulate all the pixels of the image, it works but I get 40 fps. While with graphics.fillrect I get 4000 fps and it's really slow and I need this to make a 3D game but it's very very slow. ‍‍‍‍‍

public class Renderer {

    private BufferedImage image = TextureLoader.load("./res/image.png");

    byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();

    public void render(Graphics2D g) {
        for(int x = 0; x < 1920; x  ) {
            for(int y = 0; y < 1080; y  ) {
                setRGB(x,y, Color.RED.getRGB());
            }
        }
        g.drawImage(image, 0, 0, 1920, 1080, null);
    }
    
    public void setRGB(int x, int y, int rgb) {
        int a = (y * 1920   x) * 3;
        pixels[a] = (byte) ((rgb >> 0) & 0xFF);
        pixels[a   1] = (byte) ((rgb >> 8) & 0xFF); 
        pixels[a   2] = (byte) ((rgb >> 16) & 0xFF);
        
    }


}

‍‍‍‍‍

CodePudding user response:

In general, setting every single pixel in a loop is a time consuming process. You could try to speed up your code by using various methods of WritableRaster but personally, I would use a 3d-library like LWJGL or even a 3d-game engine.

CodePudding user response:

Generally it's not a good idea to use Java's provided libraries when one wants to create a 3D game. They are very limited and have poor performance. I would advise looking at third-party libraries such as LWJGL. To replace the Java graphics libraries, use OpenGL and GLFW.

There are many tutorials on OpenGL which will help you learn, such as ThinMatrix's tutorials.

If you don't want to do all the work yourself, try a game engine or framework such as libGDX or jmonkeyengine, which are already optimized and provide an easy way to make your 3D game.

  • Related