سؤال

تخيل هذا. لدي بكسل من اللون (255،0،0) [أحمر]. لا أحد يرسم عليه باللون الأبيض مع * ألفا. أعرف لون الخلفية ، وأنا أعلم بلونه الذي تم رسمه ، أحتاج إلى الحصول على ألفا من اللون المرسومة على اللون. كيف؟

حتى الآن لدينا:

$im = imagecreatefrompng('public/images/bg-tmp.png');

// we need to find a nearest match for this array in every pixel
/*$colors = array(
    array(255, 255, 255, 100),
    array(255, 255, 255, 75),
    array(255, 255, 255, 50),
 array(255, 255, 255, 25),
    array(255, 255, 255, 0),
);*/

// finding out the pixel color
$rgb = imagecolorat($im, 0, 6);

$r  = ($rgb >> 16) & 0xFF;
$g  = ($rgb >> 8) & 0xFF;
$b  = $rgb & 0xFF;

var_dump($r, $g, $b);

موافق. لذلك أحرز تقدمًا.

$im = imagecreatefrompng('public/images/bg-tmp.png');

$pixels = array();

for($y = 0; $y < 24; $y++)
{
 for($x = 0; $x < 24; $x++)
 {
  $rgb  = imagecolorat($im, $x, $y);

// قيم RGB الثلاثة الأولى هي ألوان الخلفية $ pixels [] = Array ($ x ، $ y ، calc_alpha_diff (0 ، 0 ، 0 ، ($ rgb >> 16) & 0xff ، ($ rgb >> 8) & 0xff ، $ rgb & 0xff)) ؛ }}

function calc_alpha_diff($R1,$G1,$B1,$R2,$G2,$B2)
{
 $color_diff = max($R1,$R2) - min($R1,$R2) + max($G1,$G2) - min($G1,$G2) + max($B1,$B2) - min($B1,$B2);

 $array  = array
 (
  100 => 510, // 1
  75 => 382, // 0.75
  50 => 256, // 0.5
  25 => 128, // 0.25
  0 => 0 // 0
 );

 // find the nearest value
 foreach($array as $key => $val)
 {
  $delta = abs($val - $color_diff);

  if(!isset($min_delta) || $min_delta > $delta)
  {
   $min_delta = $delta;
   $alpha  = $key;
  }
 }

 return $alpha;
}

$im  = imagecreatetruecolor(24, 24);

foreach($pixels as $p)
{
 if($p[2] != 0)
 {
  imagesetpixel($im, $p[0], $p[1], imagecolorallocatealpha($im, 255, 0, 0, $p[2]));
 }
}

// make image transperant
imagecolortransparent($im, 0);

imagepng($im);
imagedestroy($im);

header('Content-type: image/png');

exit;

سيوفر لك هذا الرمز نتيجة جيدة. ومع ذلك ، ليست جيدة بما فيه الكفاية. يرجى اقتراح تحسينات.

هل كانت مفيدة؟

المحلول

تم العثور على الجواب هنا:

خوارزمية لخلط الألوان المضافة لقيم RGB

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top