通过PHP将JPEG图像转换为更少的颜色


Converting a JPEG image to less colours via PHP

我需要减少图像中的颜色数量,因为现在我的图像中的字母有许多黑色的阴影,我需要把所有的深色变成实际的黑色等,所以我猜减少颜色的数量,我使用以下代码(它裁剪图片,应该减少颜色的数量),但它似乎带回来完全相同的图像?

<?
$filename = 'img1.jpg';
list($current_width, $current_height) = getimagesize($filename);
$C = 8;
$A = 5;
$B = 52;
$D = 11;
// Resample the image
$canvas = imagecreatetruecolor($B, $D);
imagetruecolortopalette($canvas, false, 20); // Supposed to only have 20 colours?? 
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $C, $A, $B, $D);
imagejpeg($canvas, "img2.jpg", 100);
echo "<img src='img2.jpg'/>";
?>

如有任何帮助,不胜感激

JPEG不是基于调色板的格式,因此调用imagetruecolortopalette的结果没有定义良好。以支持调色板颜色的图像格式生成输出,如PNG或GIF。

(另外,如果您只是处理静态图像,为什么不直接在编辑器中修复图像呢?)

前段时间我写了一个函数来做这个。

function alpha($image,$r=0,$g=0,$b=0){
$width=imagesx($image);
$height=imagesy($image);
$aw=0;
$ah=0;
for(;;){
if ($aw==$width) {$aw=0; $ah++;}
if ($ah==$height) break;
$rgb = imagecolorat($image, $aw, $ah);
$colors = imagecolorsforindex($image, $rgb);
$ar = $colors['red'];
$ag = $colors['green'];
$ab = $colors['blue'];
$ar+=$r;
$ag+=$g;
$ab+=$b;
if ($ar>255) $ar=255;
if ($ag>255) $ag=255;
if ($ab>255) $ab=255;
if ($ar<0) $ar=0;
if ($ag<0) $ag=0;
if ($ab<0) $ab=0;
$newcolor = imagecolorallocate($image, $ar, $ag, $ab);
$black = imagecolorallocate($image, 0, 55, 0);
imagesetpixel ($image , $aw , $ah , $newcolor );
$aw++;
}//end loop
return $image;}

你可以调整整个图像的RGB正或负int

例如,删除红色

alpha($image,-225,0,0);

注意函数名:alpha,实际上与alpha通道没有任何关系。它可以使图像看起来像具有alpha通道效果。