【发布时间】:2015-10-28 09:28:38
【问题描述】:
使用 GD 函数更改图像的颜色。由于多次迭代,创建需要大量时间。正如下面提到的脚本粉红色(255,0,255)和附近的颜色替换为其他动态颜色。脚本输出是正确的,但如前所述,创建输出图像需要大量时间。
是否可以减少彩色图像的创建时间 可更改的功能还是我们可以更改任何代码部分?
function changeImageColor($oldColorTriplet, $newColorTriplet, $hueError = 0.4){
if (!$this->isImageCreated())
return false;
$oldColorHSL = $this->RGBtoHSL($oldColorTriplet[0], $oldColorTriplet[1], $oldColorTriplet[2]);
$newColorHSL = $this->RGBtoHSL($newColorTriplet[0], $newColorTriplet[1], $newColorTriplet[2]);
$cx = $this->width();
$cy = $this->height();
for ($x = 0; $x < $cx; $x++) {
for ($y = 0; $y < $cy; $y++) {
$pixel = imagecolorsforindex($this->handle, imagecolorat($this->handle, $x, $y));
$currentColorHSL = $this->RGBtoHSL($pixel['red'], $pixel['green'], $pixel['blue']);
if (($currentColorHSL[0] >= $oldColorHSL[0] - $hueError)
&& ($oldColorHSL[0] + $hueError >= $currentColorHSL[0])) {
//$color = $this->HSLtoRGB($newColorHSL[0], $newColorHSL[1], $currentColorHSL[2]);
$color = $newColorTriplet;
$color = imagecolorallocatealpha($this->handle, $color[0], $color[1], $color[2], $pixel['alpha']);
imagesetpixel($this->handle, $x, $y, $color);
}
}
}
return true;
}
function RGBtoHSL( $r, $g, $b ){
$r /= 255;
$g /= 255;
$b /= 255;
$max = max( $r, $g, $b );
$min = min( $r, $g, $b );
$l = ( $max + $min ) / 2;
$d = $max - $min;
if( $d == 0 ){
$h = $s = 0;
} else {
$s = $d / ( 1 - abs( 2 * $l - 1 ) );
switch( $max ){
case $r:
$h = 60 * fmod( ( ( $g - $b ) / $d ), 6 );
if ($b > $g) {
$h += 360;
}
break;
case $g:
$h = 60 * ( ( $b - $r ) / $d + 2 );
break;
case $b:
$h = 60 * ( ( $r - $g ) / $d + 4 );
break;
}
}
return array( round( $h, 2 ), round( $s, 2 ), round( $l, 2 ) );
}
function HSLtoRGB( $h, $s, $l ){
$c = ( 1 - abs( 2 * $l - 1 ) ) * $s;
$x = $c * ( 1 - abs( fmod( ( $h / 60 ), 2 ) - 1 ) );
$m = $l - ( $c / 2 );
if ( $h < 60 ) {
$r = $c;
$g = $x;
$b = 0;
} else if ( $h < 120 ) {
$r = $x;
$g = $c;
$b = 0;
} else if ( $h < 180 ) {
$r = 0;
$g = $c;
$b = $x;
} else if ( $h < 240 ) {
$r = 0;
$g = $x;
$b = $c;
} else if ( $h < 300 ) {
$r = $x;
$g = 0;
$b = $c;
} else {
$r = $c;
$g = 0;
$b = $x;
}
$r = ( $r + $m ) * 255;
$g = ( $g + $m ) * 255;
$b = ( $b + $m ) * 255;
return array( floor( $r ), floor( $g ), floor( $b ) );
}
【问题讨论】:
-
您可以尝试使用 fxImage 例程phpimagick.com/Imagick/fxImage,但不能保证更快。