Image Processing Computer Science

Convert a Color Image to a Grayscale Image

This PHP example displays the code for an example program that demonstrates how to convert a color image to a grayscale image with GD.

ConvertColorToGray.php

<?php
  function CreateGrayScaleImage($qColorImage) {
    $iImageWidth        = ImageSX($qColorImage);
    $iImageHeight       = ImageSY($qColorImage);
    $qGrayScaleImage    = ImageCreate($iImageWidth, $iImageHeight);
    for ($iC = 0; $iC < 256; ++$iC) {
      ImageColorAllocate($qGrayScaleImage, $iC, $iC, $iC);
    }
    for ($j = 0; $j < $iImageHeight; ++$j) {
      for ($i = 0; $i < $iImageWidth; ++$i) {
        $qColor  = ImageColorAt($qColorImage, $i, $j);
        $iRed    = (($qColor >> 16) & 0xFF);
        $iGreen  = (($qColor >> 8) & 0xFF);
        $iBlue   = ($qColor & 0xFF);
        $iGray   = IntVal(round(0.299*$iRed + 0.587*$iGreen + 0.114*$iBlue));
        ImageSetPixel($qGrayScaleImage, $i, $j, $iGray);
      }
    }
    return $qGrayScaleImage;
  }

  $qOriginalImage = ImageCreateFromPng("triumph_of_christianity.png");

  $qGrayImage = CreateGrayScaleImage($qOriginalImage);

  $iW            = ImageSX($qOriginalImage);
  $iH            = ImageSY($qOriginalImage);
  $qCompareImage = ImageCreateTrueColor(2*$iW, $iH);

  // Copy the original image and the gray scale image
  ImageCopyMerge($qCompareImage, $qOriginalImage, 0, 0, 0, 0, $iW, $iH, 100);
  ImageCopyMerge($qCompareImage, $qGrayImage, $iW, 0, 0, 0, $iW, $iH, 100);

  Header('Content-type: image/png');
  ImagePng($qCompareImage);
  ImageDestroy($qCompareImage);
  ImageDestroy($qOriginalImage);
  ImageDestroy($qGrayImage);
?>
 
 

Output

 
 

© 2007–2022 XoaX.net LLC. All rights reserved.