Support

Account

Home Forums Front-end Issues Convert hexadecimal value to CMYK

Solved

Convert hexadecimal value to CMYK

  • Hello everyone.

    Iā€™m using color picker in a repeater field and I want to convert hexadecimal value to CMYK. I wonder how I can do this. Can you help me?

    Thank you.

  • Thank you @john!

    I have found this piece of code, but I wonder how can I adjust the ‘sub_field’ in my code.

  • You can’t. You add the code to your site and then use it with the result from the field.

    
    echo rgb2cmyk(hex2rgb(get_sub_field('your-field-name')));
    
  • in function.php :

    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,
    	);
     }
     
     echo rgb2cmyk(hex2rgb(get_sub_field('color_hex')));

    page template :

    <span class="cmyk"><?php rgb2cmyk('color_hex', $post->ID);?></span>

    And I have some errors: Array to string conversion. What I am doing wrong?

  • Yes, that function returns a array, sorry, that depends on what you want to do with the values returned.

  • Basically when I choose a hex color from the color picker, I want to return this converted value in CMYK format šŸ™‚

  • 
    $cmyk = rgb2cmyk(hex2rgb(get_sub_field('your-field-name')));
    foreach ($cmyk as $i => $v) {
      echo $i,'=',$v,'<br />';
    }
    
  • As an example the value: #060e5b returns me

    c=0.93406593406593
    m=0.84615384615385
    y=0
    k=164

    But I want to return : cmyk(93,85,0,64) Any idea? šŸ™‚

    Regards

  • Information on what you want to output is what I was trying to get you to tell me.

    
    $cmyk = rgb2cmyk(hex2rgb(get_sub_field('your-field-name')));
    foreach ($cmyk as $i => $v) {
      echo 'cmyk('.implode(',', $cmyk).')';
    }
    
  • @john thank you for your help. In my case, I don’t think that I need the foreach ($cmyk as $i => $v), because returns the value a lot of times and I want this value, only one time. šŸ™‚

Viewing 11 posts - 1 through 11 (of 11 total)

You must be logged in to reply to this topic.