PHP:HEX到CMYK

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (94)

如何在PHP中将HEX颜色值转换为CMYK等效值?

我想写一个能做到这一点的函数。但我不知道如何将十六进制转换为CMYK

eg: 
<?php

hex2CMYK('#000000'); //result: array('0.0','0.0','0.0','0.0');

?>
提问于
用户回答回答于
function hex2rgb($hex) {
   $color = str_replace('#','',$hex);
   $rgb = array(
      'r' => hexdec(substr($color,0,2)),
      'g' => hexdec(substr($color,2,2)),
      'b' => hexdec(substr($color,4,2)),
   );
   return $rgb;
}

function rgb2cmyk($var1,$g=0,$b=0) {
   if (is_array($var1)) {
      $r = $var1['r'];
      $g = $var1['g'];
      $b = $var1['b'];
   } else {
      $r = $var1;
   }
   $cyan = 255 - $r;
   $magenta = 255 - $g;
   $yellow = 255 - $b;
   $black = min($cyan, $magenta, $yellow);
   $cyan = @(($cyan    - $black) / (255 - $black));
   $magenta = @(($magenta - $black) / (255 - $black));
   $yellow = @(($yellow  - $black) / (255 - $black));
   return array(
      'c' => $cyan,
      'm' => $magenta,
      'y' => $yellow,
      'k' => $black,
   );
}

$color=rgb2cmyk(hex2rgb('#FF0000'));
用户回答回答于

我刚刚遇到这个因为我正在寻找转换脚本。但是,Mark Ba​​ker在答案中的rgb2cmyk函数似乎没有计算出正确的值。我将结果与多个在线计算器进行了比较,为了得到正确的值,我必须修改这个函数:

function rgb2cmyk($var1,$g=0,$b=0) {
    if (is_array($var1)) {
            $r = $var1['r'];
            $g = $var1['g'];
            $b = $var1['b'];
    } else {
            $r = $var1;
    }
    $cyan = 1 - $r/255;
    $magenta = 1 - $g/255;
    $yellow = 1 - $b/255;
    $black = min($cyan, $magenta, $yellow);
    $cyan = @round(($cyan - $black) / (1 - $black) * 100);
    $magenta = @round(($magenta - $black) / (1 - $black) * 100);
    $yellow = @round(($yellow - $black) / (1 - $black) * 100);
    $black = round($black * 100);
    return array(
            'c' => $cyan,
            'm' => $magenta,
            'y' => $yellow,
            'k' => $black,
    );
}

现在,我不完全理解我在这里做了什么,但它似乎输出正确的值(与所有其他在线计算器相比)。

扫码关注云+社区

领取腾讯云代金券