Search code examples
javahexagonal-tiles

creating tiles using bufferedImage in java


public static BufferedImage split(BufferedImage img) {
   BufferedImage pic = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
   Graphics g = pic.getGraphics();

    int width = 2000/2;
    int height = 2000/2;
    int imageW = pic.getWidth();
    int imageH = pic.getHeight();
                // Tile the image to fill our area.
    for (int x = 0; x < width; x += imageW) {
        for (int y = 0; y < height; y += imageH) {
            g.drawImage(pic, x, y, null);
        }
    }  
    return pic ;  
}  

the point of the code is to create a tile of 2x2 of the image (same image reproduce at a smaller size in a 2x2 grid). i want to updated pic so i can print it onto a jpanel. all i get is black image. can someone tell me whats wrong with the code. or tell me how to create a better piece of code.


Solution

  • I want to make four smaller images of the original and place it in a grid of 2x2 that is the same size as the original image

    Something like...

    public static BufferedImage split(BufferedImage img) {
        BufferedImage pic = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics g = pic.getGraphics();
    
        int width = pic.getWidth() / 4;
        int height = pic.getHeight() / 4;
    
        Image scaled = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
    
        // Tile the image to fill our area.
        for (int x = 0; x < pic.getWidth(); x += width) {
            for (int y = 0; y < pic.getHeight(); y += height) {
                g.drawImage(scaled, x, y, null);
            }
        }
        g.dispose();
        return pic;
    }
    

    You may also like to have a look at Java: maintaining aspect ratio of JPanel background image and Quality of Image after resize very low -- Java for more details about how you can improve the scaling algorithm