【问题标题】:How can I give a color to imagecolorallocate?如何为 imagecolorallocate 提供颜色?
【发布时间】:2011-02-26 19:23:34
【问题描述】:

我有一个 PHP 变量,其中包含有关颜色的信息。例如$text_color = "ff90f3"。现在我想把这个颜色给imagecolorallocateimagecolorallocate 是这样工作的:

imagecolorallocate($im, 0xFF, 0xFF, 0xFF);

所以,我正在尝试执行以下操作:

$r_bg = bin2hex("0x".substr($text_color,0,2));
$g_bg = bin2hex("0x".substr($text_color,2,2));
$b_bg = bin2hex("0x".substr($text_color,4,2));
$bg_col = imagecolorallocate($image, $r_bg, $g_bg, $b_bg);

它不起作用。为什么?我在没有 bin2hex 的情况下也尝试过,它也没有用。有人可以帮我吗?

【问题讨论】:

  • bin2hex函数有什么作用?
  • 我把 bin2hex 放在那里把字符串转换成十六进制数,应该给 imagecolorallocate。
  • “字符串”和“十六进制数”有什么区别?我问的是这个功能是做什么的,而不是你为什么使用它。它至少返回什么?在这种情况下,我的意思是
  • 如果我使用它“将字符串转换为十六进制”而不是“将字符串转换为十六进制”。它接受字符串并返回十六进制。它就是这样做的。
  • 想想你给这个函数输入了什么字符串。

标签: php string colors hex


【解决方案1】:

来自http://forums.devshed.com/php-development-5/gd-hex-resource-imagecolorallocate-265852.html

function hexColorAllocate($im,$hex){
    $hex = ltrim($hex,'#');
    $r = hexdec(substr($hex,0,2));
    $g = hexdec(substr($hex,2,2));
    $b = hexdec(substr($hex,4,2));
    return imagecolorallocate($im, $r, $g, $b); 
}

用法

$img = imagecreatetruecolor(300, 100);
$color = hexColorAllocate($img, 'ffff00');
imagefill($img, 0, 0, $color); 

颜色可以传递为十六进制 ffffff#ffffff

【讨论】:

    【解决方案2】:

    使用hexdec()(例如:hexdec("a0")

    http://fr2.php.net/manual/en/function.hexdec.php

    【讨论】:

      【解决方案3】:
      function hex2RGB($hexStr, $returnAsString = false, $seperator = ',') {
          $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string
          $rgbArray = array();
          if (strlen($hexStr) == 6) { //If a proper hex code, convert using bitwise operation. No overhead... faster
              $colorVal = hexdec($hexStr);
              $rgbArray['red'] = 0xFF & ($colorVal >> 0x10);
              $rgbArray['green'] = 0xFF & ($colorVal >> 0x8);
              $rgbArray['blue'] = 0xFF & $colorVal;
          } elseif (strlen($hexStr) == 3) { //if shorthand notation, need some string manipulations
              $rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
              $rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
              $rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));
          } else {
              return false; //Invalid hex color code
          }
          return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray; // returns the rgb string or the associative array
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-16
        • 2022-01-03
        • 2018-03-07
        • 2013-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-26
        • 1970-01-01
        相关资源
        最近更新 更多