Class ColorContrastCalculator

java.lang.Object
com.itextpdf.kernel.contrast.ColorContrastCalculator

public final class ColorContrastCalculator extends Object
Utility class for calculating color contrast ratios according to the Web Content Accessibility Guidelines (WCAG) 2.1.

The contrast ratio ranges from 1:1 (no contrast) to 21:1 (maximum contrast between black and white).

  • Method Details

    • contrastRatio

      public static double contrastRatio (DeviceRgb color1, DeviceRgb color2)
      Calculates the contrast ratio between two colors according to WCAG 2.1 guidelines.

      The contrast ratio is calculated as (L1 + 0.05) / (L2 + 0.05), where L1 is the relative luminance of the lighter color and L2 is the relative luminance of the darker color.

      The resulting value ranges from 1:1 (identical colors) to 21:1 (black and white).

      Parameters:
      color1 - the first color to compare, must not be null
      color2 - the second color to compare, must not be null
      Returns:
      the contrast ratio between the two colors, ranging from 1.0 to 21.0
      Throws:
      IllegalArgumentException - if either color is null
    • contrastRatio

      public static double contrastRatio (double r1, double g1, double b1, double r2, double g2, double b2)
      Calculates the contrast ratio between two RGB colors according to WCAG 2.1 guidelines.

      The contrast ratio is calculated as (L1 + 0.05) / (L2 + 0.05), where L1 is the relative luminance of the lighter color and L2 is the relative luminance of the darker color.

      Parameters:
      r1 - red component of the first color (0-1)
      g1 - green component of the first color (0-1)
      b1 - blue component of the first color (0-1)
      r2 - red component of the second color (0-1)
      g2 - green component of the second color (0-1)
      b2 - blue component of the second color (0-1)
      Returns:
      the contrast ratio between the two colors, ranging from 1.0 to 21.0