'BufferedImage Kernel - Image Processing

I would like to create an image filter and have read the following Wikipedia article. I wanted to test the example from Wikipedia and get an incorrect result.

https://en.wikipedia.org/wiki/Kernel_(image_processing)

(For some reason I cannot upload images)

Result: https://imgur.com/FiYFuZS

Expected result: https://upload.wikimedia.org/wikipedia/commons/2/20/Vd-Rige1.png

I've also read the following source and still do not know how to fix it :/

Bluring a Java buffered image

        URL url = new URL("https://upload.wikimedia.org/wikipedia/commons/5/50/Vd-Orig.png");
        BufferedImage image = ImageIO.read(url);

        float[][] kernel = {
            {0, -1, 0},
            {-1, 4, -1},
            {0, -1, 0}
        };

        int w = image.getWidth();
        int h = image.getHeight();

        // Center point
        int cx = kernel.length / 2;
        int cy = kernel[0].length / 2;
        
        BufferedImage cImage = new BufferedImage(w, h, image.getType());
        
        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                float r = 0;
                float g = 0;
                float b = 0;
                for (int dx = -cx; dx <= cx; dx++) {
                    for (int dy = -cy; dy <= cy; dy++) {
                        float e = kernel[dx + cx][dy + cy];
                        int xImage = x + dx;
                        int yImage = y + dy;
                        if (xImage < 0 || xImage >= w || yImage < 0 || yImage >= h) {
                            continue;
                        }
                        Color pixel = new Color(image.getRGB(xImage, yImage));
                        r += pixel.getRed() * e;
                        g += pixel.getGreen() * e;
                        b += pixel.getBlue() * e;
                    }
                }

                // Boundaries
                r = Math.min(255, Math.max(0, r));
                g = Math.min(255, Math.max(0, g));
                b = Math.min(255, Math.max(0, b));

                Color newPixel = new Color((int) r, (int) g, (int) b);
                cImage.setRGB(x, y, newPixel.getRGB());
            }
        }
        ImageIO.write(cImage, "png", Files.newOutputStream(Path.of("c.png")));


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source