Code to change colour image to black & white

Discussion in 'PHP' started by GloBleeOne, Dec 22, 2007.

  1. #1
    Is there any code I can use to change a colour image on a web page to a black & white one, without having to have 2 of the same images on our server?
     
    GloBleeOne, Dec 22, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    nico_swd, Dec 22, 2007 IP
  3. coderbari

    coderbari Well-Known Member

    Messages:
    3,168
    Likes Received:
    193
    Best Answers:
    0
    Trophy Points:
    135
    #3
    
    <?php
    // The file you are grayscaling
    $file = 'yourfile.jpg';
    
    // This sets it to a .jpg, but you can change this to png or gif if that is what you are working with
    header('Content-type: image/jpeg');
    
    // Get the dimensions
    list($width, $height) = getimagesize($file);
    
    // Define our source image
    $source = imagecreatefromjpeg($file);
    
    // Creating the Canvas
    $bwimage= imagecreate($width, $height);
    
    //Creates the 256 color palette
    for ($c=0;$c<256;$c++)
    {
    $palette[$c] = imagecolorallocate($bwimage,$c,$c,$c);
    }
    
    //Creates yiq function
    function yiq($r,$g,$b)
    {
    return (($r*0.299)+($g*0.587)+($b*0.114));
    }
    
    //Reads the origonal colors pixel by pixel
    for ($y=0;$y<$height;$y++)
    {
    for ($x=0;$x<$width;$x++)
    {
    $rgb = imagecolorat($source,$x,$y);
    $r = ($rgb >> 16) & 0xFF;
    $g = ($rgb >> 8) & 0xFF;
    $b = $rgb & 0xFF;
    
    //This is where we actually use yiq to modify our rbg values, and then convert them to our grayscale palette
    $gs = yiq($r,$g,$b);
    imagesetpixel($bwimage,$x,$y,$palette[$gs]);
    }
    }
    
    // Outputs a jpg image, but you can change this to png or gif if that is what you are working with
    imagejpeg($bwimage);
    ?>
    
    PHP:
    Got this from here.
    http://php.about.com/od/gdlibrary/ss/grayscale_gd.htm
     
    coderbari, Dec 22, 2007 IP
  4. GloBleeOne

    GloBleeOne Peon

    Messages:
    286
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Thanks guys, very helpful. I will try to get this going on my site now.
     
    GloBleeOne, Dec 22, 2007 IP
  5. GloBleeOne

    GloBleeOne Peon

    Messages:
    286
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #5
    GloBleeOne, Dec 22, 2007 IP
  6. GTWebs

    GTWebs Peon

    Messages:
    43
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    I am going to use this in a job.

    Thanks
     
    GTWebs, Dec 23, 2007 IP