-1

So today I started with a new project. I want to make a simple heightmap generator in java, so I tried the following:

    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;

    public class Heightmap {


    public static int width = 200;
    public static int height = 200;

    public static void main(String[] args) {

        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY );
        for(int x = 0; x < width; x++){
            for(int y = 0; y < height; y++){
                bufferedImage.setRGB(x, y, (byte )(Math.random() * 256 + 128) ); // + 128 because byte goes from -128 to 127
            }
        }

        File outputFile = new File("heightmap.png");
        try { 
            ImageIO.write(bufferedImage, "png", outputFile);
        }catch (IOException ioex){
            ioex.printStackTrace();
        }
    }
}

The code is very simple, I plan to try perlin noise as the next step. But first I need to resolve this problem: Generated Heightmap

The pixels in heightmap.png are either completely white, or completely black. There's no grays in the image, which of course is necessary in a heightmap. Does anyone know what I did wrong?

is it the BufferedImage.TYPE_BYTE_GRAY part? If so, what should I use instead?

Siarl
  • 44
  • 1
  • 7

1 Answers1

1

After a friend set me on the right track, I found the solution.

Instead of BufferedImage.TYPE_BYTE_GRAY I used BufferdImage.TYPE_INT_RGB. So this is indeed where I went wrong. Also I added the object Color randomColor, wherein the RGB values all share the same integer with a value from 0 to 255. Then in BufferedImage.setRGB I use the color code of randomColor (so R,G,B = 255 gives #FFFFFF, which is white) as the value of pixel (x,y):

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Heightmap {


public static int width = 200;
public static int height = 200;

public static void main(String[] args) {

    BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB );
    for(int x = 0; x < width; x++){
        for(int y = 0; y < height; y++){
            int randomValue = (int)(Math.random() * 256);
            Color randomColor = new Color( randomValue, randomValue, randomValue);

            bufferedImage.setRGB(x, y, randomColor.getRGB());
        }
    }

    File outputFile = new File("heightmap.png");
    try { 
        ImageIO.write(bufferedImage, "png", outputFile);
    }catch (IOException ioex){
        ioex.printStackTrace();
    }




}

}

Now the heightmap.png gives what I expected: Heightmap.png

Siarl
  • 44
  • 1
  • 7