How to invert RGB hex values by contrast in PHP

str_pad adds characters on the right by default — its optional $pad_type argument defaults to STR_PAD_RIGHT.

You need to force it add zeros on the left:

str_pad(base_convert(255 - $c, 10, 16), 2, '0', STR_PAD_LEFT)

Your example in details:

  • Input: 6ff060, taking only the G value into consideration: $c = 0xf0 (decimal: 240).
  • 255 - 240 = 15 (hex: f)
  • base_convert(255 - $c, 10, 16) produces: 'f' (as string!)
  • str_pad(base_convert(255 - $c, 10, 16), 2, '0') adds one zero on the right, thus producing 'f0'.
  • Setting $pad_type = STR_PAD_LEFT fixes the problem.

Tags:

Algorithm

Php

Hex