Author Topic: "Is black or white best against this RGB set?" -- algorithm  (Read 368 times)

Andrew Stephenson

  • Jr. Member
  • **
  • Posts: 54
  • Karma: +1/-0
    • View Profile
"Is black or white best against this RGB set?" -- algorithm
« on: November 27, 2023, 03:38:56 pm »
If you need to make foreground text &c contrast well against a particular RGB combo, try this.  HTH.

/* BEST_FG -- 'C' code to return RGB "black" or "white" to contrast with a given colour.
By Andrew Stephenson, supplied 2023-11-27, tweaked 30-11-23.  Salvaged from old app. */

/* Computes RGB**2 (ideally, RGB**2.5) weighted R 29.9%, G 58.7%, B 11.4%. */

#if 1   /* Original version */

#define   WT_R   4899      /* 16384 * 0.299 */
#define   WT_G   9617      /* 16384 * 0.587 */
#define   WT_B   1868      /* 16384 * 0.114 */
#define   WT_REF   266342400   /* Weighted reference (16384 * 127.5**2 * 1) */

#else   /* Modified (untested) version, hopefully with fewer rounding errors */

#define   WT_R   299      /* 1000 * 0.299 */
#define   WT_G   587      /* 1000 * 0.587 */
#define   WT_B   114      /* 1000 * 0.114 */
#define   WT_REF   16256250   /* Weighted reference (1000 * 127.5**2 * 1) */

#endif

typedef unsigned char
   u_8;
typedef unsigned long
   u_32;
typedef struct
   {
   u_8   Red, Green, Blue;
   }
   BG,         /* Background colour, any RGB (supplied) */
   FG;         /* Foreground colour, black/white (returned) */

FG.Red = FG.Green = FG.Blue =
   (
      (
      (u_32) BG.Red * (u_32) BG.Red * (u_32) WT_R +
      (u_32) BG.Green * (u_32) BG.Green * (u_32) WT_G +
      (u_32) BG.Blue * (u_32) BG.Blue * (u_32) WT_B
      )
   >= (u_32) WT_REF ? (u_8) 0x00 : (u_8) 0xFF
   );

/* End sample */
« Last Edit: November 30, 2023, 03:21:49 pm by Andrew Stephenson »

Andrew Stephenson

  • Jr. Member
  • **
  • Posts: 54
  • Karma: +1/-0
    • View Profile
Re: "Is black or white best against this RGB set?" -- algorithm
« Reply #1 on: November 29, 2023, 05:06:16 pm »
While rescuing ancient material from sundry lurk-holes, I came across the attached file generated during tests of the app which incorporated this algorithm.  I see conversion of HTML to PDF has bent the layout.  HTH.  (If nothing else, at least it looks pretty.)