【问题标题】:How to convert a "true-color" image to a "black-and-white" image, with PHP?如何使用 PHP 将“真彩色”图像转换为“黑白”图像?
【发布时间】:2016-11-25 20:19:22
【问题描述】:

首先,我有一个原始图像,它是一个真彩色图像。保存为JPEG格式:

此原始图片保存在:24 位 图像中。


然后,我可以在运行这个简单的脚本后将其转换为 灰度 图像:

<?php 

$source_file = "1.JPG";

$im = ImageCreateFromJpeg($source_file); 

$imgw = imagesx($im);
$imgh = imagesy($im);

for ($i=0; $i<$imgw; $i++)
{
        for ($j=0; $j<$imgh; $j++)
        {

                // Get the RGB value for current pixel

                $rgb = ImageColorAt($im, $i, $j); 

                // Extract each value for: R, G, B

                $rr = ($rgb >> 16) & 0xFF;
                $gg = ($rgb >> 8) & 0xFF;
                $bb = $rgb & 0xFF;

                // Get the value from the RGB value

                $g = round(($rr + $gg + $bb) / 3);

                // Gray-scale values have: R=G=B=G

                $val = imagecolorallocate($im, $g, $g, $g);

                // Set the gray value

                imagesetpixel ($im, $i, $j, $val);
        }
}

header('Content-type: image/jpeg');
imagejpeg($im);

?>

结果如下:

此灰度图片保存在:8 位 图像中。


现在,我想将其转换为真实 黑白图像:

此黑白图片保存在:1 位 图像中。


你能告诉我:如何使用 PHP 将真彩色图像转换为黑白图像

【问题讨论】:

标签: php image colors gd


【解决方案1】:

在您的代码中将灰度颜色四舍五入为黑色或白色。 (根据您的要求更改或更改 if($g> 0x7F))

 $g = (r + g + b) / 3
    if($g> 0x7F) //you can also use 0x3F 0x4F 0x5F 0x6F its on you 
   $g=0xFF;
   else
   $g=0x00;

你的完整代码应该是这样的:

<?php 

$source_file = "1.JPG";

$im = ImageCreateFromJpeg($source_file); 

$imgw = imagesx($im);
$imgh = imagesy($im);

for ($i=0; $i<$imgw; $i++)
{
        for ($j=0; $j<$imgh; $j++)
        {

                // Get the RGB value for current pixel

                $rgb = ImageColorAt($im, $i, $j); 

                // Extract each value for: R, G, B

                $rr = ($rgb >> 16) & 0xFF;
                $gg = ($rgb >> 8) & 0xFF;
                $bb = $rgb & 0xFF;

                // Get the value from the RGB value

                $g = round(($rr + $gg + $bb) / 3);

                // Gray-scale values have: R=G=B=G

                 //$g = (r + g + b) / 3
    if($g> 0x7F) //you can also use 0x3F 0x4F 0x5F 0x6F its on you 
   $g=0xFF;
   else
   $g=0x00;



                $val = imagecolorallocate($im, $g, $g, $g);

                // Set the gray value

                imagesetpixel ($im, $i, $j, $val);
        }
}

header('Content-type: image/jpeg');
imagejpeg($im);

?>

您也可以使用以下替代代码逻辑

<?php 

header("content-type: image/jpeg");
$img = imagecreatefromjpeg('1.jpg');
imagefilter($img, IMG_FILTER_GRAYSCALE); //first, convert to grayscale
imagefilter($img, IMG_FILTER_CONTRAST, -255); //then, apply a full contrast
imagejpeg($img);

?>

【讨论】:

    猜你喜欢
    • 2011-02-11
    • 2021-05-02
    • 2010-10-08
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    相关资源
    最近更新 更多