Solve alpha for contrast

Find a translucent foreground that reaches the target ratio, then verify the representation you will store or send.

Before

Translucent text must be measured after compositing.

alpha 0.503.98:1AA fail

Serialized result

Translucent text must be measured after compositing.

#0000008a4.61:1AA pass

Target above the threshold, then verify the bytes

Solving for 4.6:1 returns alpha 0.541176470588. Eight-bit alpha becomes #0000008a, whose composited ratio is 4.607518093747374:1.

Solve, serialize, parse, and measure again

The solver searches continuous alpha. The hexadecimal handoff quantizes that value, so the final check belongs after serialization.

<?php

use PhpColor\Color\Color;
use PhpColor\Color\Contrast\ContrastSolver;

$foreground = Color::parse('#000000');
$background = Color::parse('#ffffff');

$alpha = ContrastSolver::requiredAlpha(
    $foreground,
    $background,
    4.6,
);

$hex = $foreground->withAlpha($alpha)->toHex(true);
$stored = Color::parse($hex);
$ratio = ContrastSolver::compositedRatio($stored, $background);

// #0000008a
// 4.607518093747374
use PhpColor\Color\Color; use PhpColor\Color\Contrast\ContrastSolver; $foreground = Color::parse('#000000'); $background = Color::parse('#ffffff'); $alpha = ContrastSolver::requiredAlpha( $foreground, $background, 4.6, ); $hex = $foreground->withAlpha($alpha)->toHex(true); $stored = Color::parse($hex); $ratio = ContrastSolver::compositedRatio($stored, $background); // #0000008a // 4.607518093747374

Opaque failure means alpha cannot solve the pair

When the fully opaque foreground remains below the target, requiredAlpha() returns 1.0. The return value does not distinguish that unsolved case, so verify the resulting ratio.

InputForeground, background, and target ratio.
Search24 binary-search iterations.
OutputAn alpha value from 0 through 1.
RequiredVerification after the final representation.

Verify the translucent result

Solve alpha against the real background