Java program to generate Sierpinski Triangle (Fractal) of specified resolution using AND algorithm, even in high resolutions ? tested for 32768x32768px with increased Java VM  heap size ? -Xmx8g option.

Sierpinski Triangle 1024x1024px Generated With AND Algorithm
Sierpinski Triangle 1024x1024px Generated With “AND” Algorithm

Note that size of image must be the power of 2, for example 1024.

import javax.imageio.ImageIO;

// 2018 TheFlyingKeyboard and released under MIT License
public class Main {
    public static void main(String[] args) {
        SierpinskiTriangle sierpinskiTriangle = new SierpinskiTriangle();
        try {
            ImageIO.write(sierpinskiTriangle.generate(1024), "png", new File("SierpinskiTriangle.png"));
        } catch (Exception e) {

import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;

// 2018 TheFlyingKeyboard and released under MIT License
public class SierpinskiTriangle {
    private final int foregroundColor;
    private final int backgroundColor;

    public SierpinskiTriangle(){
        this.foregroundColor = Color.BLACK.getRGB();
        this.backgroundColor = Color.WHITE.getRGB();


    public SierpinskiTriangle(final Color foregroundColor, final Color backgroundColor){
        this.foregroundColor = foregroundColor.getRGB();
        this.backgroundColor = backgroundColor.getRGB();

    public BufferedImage generate(final int triangleSize){
        BufferedImage bufferedImage = new BufferedImage(triangleSize, triangleSize, BufferedImage.TYPE_INT_RGB);
        int[] imagePixelData = ((DataBufferInt) bufferedImage.getRaster().getDataBuffer()).getData();

        double counter = 0;
        for(int x = 0; x < triangleSize; ++x){
            for(int y = 0; y < triangleSize; ++y){
                if((x & y) == 0){
                    imagePixelData[y * triangleSize + x] = foregroundColor;
                    imagePixelData[y * triangleSize + x] = backgroundColor;


            System.out.println((counter / (triangleSize * triangleSize)) * 100.0f + "%");

        return bufferedImage;


Java Sierpinski Triangle AND
Tagged on:             

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.