Search code examples
javaarraysimagepixel

how do you create an image from scratch?


I've been searching for about half a week now, and the only things I could find was using so-called "pixel arrays," yet not one topic said anything about how to make said array. I don't want to edit a picture - I want to create one from scratch.

I've made a little program that creates continent-based maps for me, and I'd like to create a map based on a smaller version of those continents (0 = blue, 1 = green, 2-5 = varying mixes of green/grey for mountains). If you want to use my variables in an example, my smaller-continent array is called "field," and I use BufferedWriter to write the continents to a file for bug-testing (0 = "-", 1 = " ", else is the same).

Could anyone please tell me, in detail, how I could do this?


Solution

  • One way to create an image from scratch is to employ the pixel arrays you spoke of with the addition of an image header.

    The image header differs between file formats, but the simplest--for example's sake--is a bitmap.

    From Wikipedia

    Bitmap file header

    This block of bytes is at the start of the file and is used to identify the file. A typical application reads this block first to ensure that the file is actually a BMP file and that it is not damaged. The first 2 bytes of the BMP file format are the character "B" then the character "M" in ASCII encoding. All of the integer values are stored in little-endian format (i.e. least-significant byte first).

    Wikipedia Table Source

    So, if you were able to write a program that constructed an array of pixels (representing the picture) and ensured that there was a bitmap file header with all the pertinent information at the head of the array, you would theoretically be able to create an image from scratch.

    Java Implementation

    A pixel is nothing more than a tuple of 3 numbers in the range of 0 - 255. Each of the 3 numbers represents Red, Green and Blue respectively.

    So, if you wanted to make an array of pixels you could create an object of type Pixel with three field members:

    private int myRed;
    private int myGreen;
    private int myBlue;
    

    Then declare an array of Pixels(after you write the correct BMP header of course) like this:

    Pixel[][] picture = new Pixel[WIDTH][HEIGHT]
    

    Taking care to account for the 2 dimensions necessary to create the picture held within the generated Pixels.

    Employing some type of OutputStream you could then write all the necessary bytes to a new File object.