面对PHP上传递十六进制颜色的问题imagecolorallocate()

时间:2017-05-10 17:31:38

标签: php

我正在尝试在PHP中创建图像,但在imagecolorallocate()函数中使用Hex颜色而不是RGB,但是我收到此错误消息:

  

警告:imagecolorallocate()需要4个参数,2个给定

你可以告诉我如何解决这个问题吗?

<?php
$dir = "maps/";

function hex2rgb($hex) {
   $hex = str_replace("#", "", $hex);

   if(strlen($hex) == 3) {
      $r = hexdec(substr($hex,0,1).substr($hex,0,1));
      $g = hexdec(substr($hex,1,1).substr($hex,1,1));
      $b = hexdec(substr($hex,2,1).substr($hex,2,1));
   } else {
      $r = hexdec(substr($hex,0,2));
      $g = hexdec(substr($hex,2,2));
      $b = hexdec(substr($hex,4,2));
   }
   $rgb = array($r, $g, $b);
   //return implode(",", $rgb);
   return $rgb; 
}
$rgb = hex2rgb("#cc0");
$im = imagecreatetruecolor(400, 400);
$red = imagecolorallocate($im, $rgb);
imagefill($im, 0, 0, $red);
// Save the image as 'simpletext.jpg'
imagejpeg($im, $dir.'image_demo.jpg');

imagedestroy($im);
?>

1 个答案:

答案 0 :(得分:2)

imagecolorallocate需要四个参数:图像 R ed值, G reen值和 B lue值。您只传递图像和表示这些颜色的数组。

尝试:

  imagecolorallocate($im, $rgb[0], $rgb[1], $rgb[2]);

Read more about imagecolorallocate