PHP GD Image into black and white


 

PHP GD Image into black and white

This example shows how to show black&white image in php gd.

This example shows how to show black&white image in php gd.

<?php

$i = new imagethumbnail_blackandwhite();

$i->open("index.jpg");

$i->setX(100);

$i->blackandwhite();

header("Content-type: image/jpeg;");

$i->imagejpeg();

class imagethumbnail {

var $filename;

var $x;

var $y;

var $image;

var $thumbnail;

function imagethumbnail() {

}

function open($filename) {

$this->filename = $filename;

$imageinfo = array();

$imageinfo = getimagesize($this->filename,$imageinfo);

$this->old_x = $imageinfo[0];

$this->old_y = $imageinfo[1];

switch ($imageinfo[2]) {

case "1": $this->image = imagecreatefromgif($this->filename); break;

case "2": $this->image = imagecreatefromjpeg($this->filename); break;

case "3": $this->image = imagecreatefrompng($this->filename); break;

}

}

function setX($x="") {

if (isset($x)) { $this->x = $x; }

return $this->x;

0

}

function setY($y="") {

if (isset($y)) { $this->y = $y; }

1

return $this->y;

}

function generate() {

2

if ($this->x > 0 and $this->y > 0) {

$new_x = $this->x;

$new_y = $this->y;

3

} elseif ($this->x > 0 and $this->x != "") {

$new_x = $this->x;

$new_y = ($this->x/$this->old_x)*$this->old_y;

4

} else {

$new_x = ($this->y/$this->old_y)*$this->old_x;

$new_y = $this->y;

5

}

$this->thumbnail = imagecreatetruecolor($new_x,$new_y);

$white = imagecolorallocate($this->thumbnail,255,255,255);

6

imagefill($this->thumbnail,0,0,$white);

 

imagecopyresampled ( $this->thumbnail, $this->image, 0, 0, 0, 0, $new_x, $new_y, $this->old_x, $this->old_y);

7

}

function imagegif($filename="") {

if (!isset($this->thumbnail)) { $this->generate(); }

8

imagetruecolortopalette($this->thumbnail,0,256);

if ($filename=="") {

imagegif($this->thumbnail);

9

} else {

imagegif($this->thumbnail,$filename);

}

0

}

function imagejpeg($filename="",$quality=80) {

if (!isset($this->thumbnail)) { $this->generate(); }

1

imagejpeg($this->thumbnail,$filename,$quality);

}

function imagepng($filename="") {

2

if (!isset($this->thumbnail)) { $this->generate(); }

if ($filename=="") {

imagepng($this->thumbnail);

3

} else {

imagepng($this->thumbnail,$filename);

}

4

}

}

class imagethumbnail_blackandwhite extends imagethumbnail {

5

function imagethumbnail_blackandwhite() {

}

function blackandwhite() {

6

if (!isset($this->thumbnail)) { $this->generate(); }

for ($x=0;$x<256;$x++) {

$palette[$x] = imagecolorallocate($this->thumbnail,$x,$x,$x);

7

}

for ($x=0;$x<imagesx($this->thumbnail);$x++) {

for ($y=0;$y<imagesy($this->thumbnail);$y++) {

8

$rgb = imagecolorat($this->thumbnail,$x,$y);

$r = ($rgb >> 16) & 0xFF;

$g = ($rgb >> 8) & 0xFF;

9

$b = $rgb & 0xFF;

$val = (($r*0.299)+($g*0.587)+($b*0.114));

imagesetpixel($this->thumbnail,$x,$y,$palette[$val]);

0

}

}

}

1

}

?>

After running the program you will get the following output

Ads