Search code examples
javaimagecolorspixel

Setting a pixel colour using hex code


So when I was a few years younger I was able to figure this out but have since forgotten how to do this. I am trying to set a pixel to a given colour using the hex code for a colour.

The basic code would be something like this:

ImageName.setRGB(x, y, hex code colour)


Solution

  • setRGB() takes 3 int values two for the coords and one to represent the color.

    Hexcodes for colors are generally made up of either 3 or 4 groupings of 2 Hex values like so:

    0xFF00FF00
    

    The above code would represent a solid green color with full alpha. This is because the first grouping of two Hex codes corresponds with that colors alpha, the second its red, third green, and fourth blue.

    So, you can put all these values into an int because an int is 32 bits long. Each hex code is 8-bits in length.

    To do this you need to shift the values to the left. Try this for our color example above:

    int color = (0xFF<<24) | (0x00<<16) | (0xFF<<8) | (0x00);
    

    Then you can use color in your call to setRGB

    ImageName.setRGB(x, y, color);