Image Processing Computer Science

Separate the RGB Color Channels

This Image Processing Reference section displays the code for an example program that demonstrates how to separate the red, green, and blue color channels in a color image with GD.

SeparateColorChannels.php

<?php
  function CreateColorChannelsImage($qOriginalImage) {
    $iWidth        = ImageSX($qOriginalImage);
    $iHeight       = ImageSY($qOriginalImage);
    $qRedImage     = ImageCreate($iWidth, $iHeight);
    $qGreenImage   = ImageCreate($iWidth, $iHeight);
    $qBlueImage    = ImageCreate($iWidth, $iHeight);
    for ($iC = 0; $iC < 256; ++$iC) {
      ImageColorAllocate($qRedImage, $iC, 0, 0);
      ImageColorAllocate($qGreenImage, 0, $iC, 0);
      ImageColorAllocate($qBlueImage, 0, 0, $iC);
    }
    for ($j = 0; $j < $iHeight; ++$j) {
      for ($i = 0; $i < $iWidth; ++$i) {
        $qColor  = ImageColorAt($qOriginalImage, $i, $j);
        $iRed    = (($qColor >> 16) & 0xFF);
        $iGreen  = (($qColor >> 8) & 0xFF);
        $iBlue   = ($qColor & 0xFF);
        ImageSetPixel($qRedImage, $i, $j, $iRed);
        ImageSetPixel($qGreenImage, $i, $j, $iGreen);
        ImageSetPixel($qBlueImage, $i, $j, $iBlue);
      }
    }
    $qChannelsImage = ImageCreateTrueColor(2*$iWidth, 2*$iHeight);
    // Copy the color channel images to the main image
    ImageCopyMerge($qChannelsImage, $qOriginalImage, 0, 0, 0, 0, $iWidth, $iHeight, 100);
    ImageCopyMerge($qChannelsImage, $qRedImage, $iWidth, 0, 0, 0, $iWidth, $iHeight, 100);
    ImageCopyMerge($qChannelsImage, $qGreenImage, 0, $iHeight, 0, 0, $iWidth, $iHeight, 100);
    ImageCopyMerge($qChannelsImage, $qBlueImage, $iWidth, $iHeight, 0, 0, $iWidth, $iHeight, 100);
    ImageDestroy($qRedImage);
    ImageDestroy($qGreenImage);
    ImageDestroy($qBlueImage);
    return $qChannelsImage;
  }

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

  $qChannelsImage = CreateColorChannelsImage($qOriginalImage);

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

Output

 
 

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