2016-07-22 182 views
2

首先,我有一個原始圖像,這是一個真彩色圖像。它被保存在JPEG格式:如何使用PHP將「真彩色」圖像轉換爲「黑白」圖像?

*#1*. The original image.

這種原始圖片保存在: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); 

?> 

而且,下面是結果:

*#2*. The gray-scale image.

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


現在,我想將其轉換成一個真正黑與白圖像:

*#3*. The black-and-white image.

這黑色和白色的圖片保存在:1位圖像。


你能告訴我:如何真彩色圖像轉換爲黑色和白色圖像,用PHP

+0

你讀過這個問題嗎? http://stackoverflow.com/q/31342505/3885509 –

+1

可能重複的[你如何將圖像轉換爲黑色和白色的PHP](http://stackoverflow.com/questions/254388/how-do-you-轉換-一個圖像到黑 - 白功能於PHP) – miken32

回答

3

朋友在您的代碼中將灰度顏色舍入爲黑色或白色。 (改變或變化,如果($克> 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); 

?> 
相關問題