Php颜色替换图像

时间:2016-09-02 02:27:24

标签: php replace colors

我有这个脚本用用户选择的另一种颜色替换黑色或白色,然而在某些颜色(紫色背景绿色书写)上工作正常它会在字母周围留下白色像素化边框? 我不知道该怎么办? 在这里看到 - http://marijasorganicpantry.com.au/imagephp.php

<?php
ob_start();
	$txtcolor=$_REQUEST['text1'];
	$r1txt=hexdec(substr($txtcolor,0,2));
    $g1txt=hexdec(substr($txtcolor,2,2));
	$b1txt=hexdec(substr($txtcolor,4,2));
	
	$backcolor=$_REQUEST['back1'];
	$r1back=hexdec(substr($backcolor,0,2));
    $g1back=hexdec(substr($backcolor,2,2));
	$b1back=hexdec(substr($backcolor,4,2));
	$imgname="demo_the-crown-prints_work-hard_5x7.jpg";
	
	$im = imagecreatefromjpeg($imgname);
	$w = imagesx($im);
	$h = imagesy($im); 
	$gd = imagecreatetruecolor($w,$h);
	imagecopyresampled($gd, $im, 0, 0, 0, 0, $w, $h, $w, $h);
	imagefilter($gd, IMG_FILTER_COLORIZE,$r1txt,$g1txt,$b1txt); 

	for($x=0;$x<$w;$x++) 
	{
		for($y=0;$y<$h;$y++)
			{
				$rgb = imagecolorat($gd, $x, $y);
				$r = ($rgb >> 16) & 0xFF;
				$g = ($rgb >> 8) & 0xFF;
				$b = $rgb & 0xFF;
				
				if ($r==255 and $g==255 and $b==255)
				{	
				$pixelColor=imagecolorallocatealpha($gd,$r1back,$g1back,$b1back,10);
				imagesetpixel($gd,$x,$y,$pixelColor);	
				}
			}
	}
	
imagejpeg($gd,NULL,100);
$outputBuffer = ob_get_clean();
$base64 = base64_encode($outputBuffer);
echo '<a id="downloadimage" style="text-decoration:none;" download>
	<img id="image2" width=150 height=250 src="data:image/jpeg;base64,'.$base64.'" />
	<li style="padding-top:7px;textalign:center;display:block;border-radius:10px;background-color:royaleblue;height:30px;width:100px;">download</li></a>';	
?>

1 个答案:

答案 0 :(得分:0)

因为在原始图像中,字母的边框不是完美的黑色,所以颜色不是

R = 0
G = 0
B = 0

我已经更改了一些原始代码以避免不必要的步骤。这是你需要的吗?

<?php
ob_start();
$txtcolor="20FF00";
$r1txt=hexdec(substr($txtcolor,0,2));
$g1txt=hexdec(substr($txtcolor,2,2));
$b1txt=hexdec(substr($txtcolor,4,2));

$backcolor="FF0ED9";
$r1back=hexdec(substr($backcolor,0,2));
$g1back=hexdec(substr($backcolor,2,2));
$b1back=hexdec(substr($backcolor,4,2));
$imgname="demo_the-crown-prints_work-hard_5x7.jpg";

$gd = imagecreatefromjpeg($imgname);
$w = imagesx($gd);
$h = imagesy($gd);
for($x=0;$x<$w;$x++) 
{
    for($y=0;$y<$h;$y++)
        {
            $rgb = imagecolorat($gd, $x, $y);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;

            if ($r>200 && $g>200 && $b>200)
            {   
                $pixelColor=imagecolorallocate($gd,$r1back,$g1back,$b1back);
                imagesetpixel($gd,$x,$y,$pixelColor);                   
            } else {
                $pixelColor=imagecolorallocate($gd,$r1txt,$g1txt,$b1txt);
                imagesetpixel($gd,$x,$y,$pixelColor);
            }
        }
}

imagejpeg($gd,'simpletext.jpg', 100);
imagepng($gd,'simpletext.png', 0);
?>

我已将结果保存在文件中,以便您了解imagejpeg和imagepng之间的质量差异