Php颜色替换上的图像


Php color replace on image

我有这个脚本,用用户选择的另一种颜色替换黑色或白色,但是在某些颜色(紫色背景绿色文字)上,它在字母周围留下一个白色像素化的边框?我不知道该怎么办?看这里- 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>';	
?>

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

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之间的质量差异