Automatically Converting Images to Black and White

Ideally you should convert your images by using one of the methods described in Creating Coloring Pages, but what if you've got THOUSANDS?  Well that could take a while.

PHP Script

Here's a simple PHP script that can be used to convert JPEG images to pure black and white GIFs.  It won't necessarily do a perfect job, but you can always tweak them later.

You can put this on your server to run it, or if you have a way of running the PHP command-line on your local machine, do it there.

All you have to do is edit the last line of the script to tell it where to start, and it will look for every jpeg, in that directory, and all those below it, and convert them into GIFs (leaving the JPEGs unchanged).

The script could also easily be modified to work with other file types, or to just clean up your existng GIFs.


function convertImage($fnIn, $fnOut) {
  list($w, $h) = getimagesize($fnIn);
  $imJPEG = imagecreatefromjpeg($fnIn);
  $imGIF = imagecreate($w, $h);
  $black = imagecolorallocate($imGIF, 0, 0, 0);
  $white = imagecolorallocate($imGIF, 255, 255, 255);
  for ($y = 0; $y < $h; $y++) {
    for ($x = 0; $x < $w; $x++) {
      $rgb = imagecolorat($imJPEG, $x, $y);
      $r = ($rgb >> 16) & 0xFF;
      $g = ($rgb >> 8) & 0xFF;
      $b = $rgb & 0xFF;
      if ($r + $g + $b < 300) {
        imagesetpixel($imGIF, $x, $y, $black);
      } else {
        imagesetpixel($imGIF, $x, $y, $white);
  imagegif($imGIF, $fnOut);

function convertImages($path) {
  foreach (glob("$path/*") as $item) {
    if (is_dir($item)) {
    } else {
      $ext = strtolower(pathinfo($item, PATHINFO_EXTENSION));
      if ($ext == "jpg" || $ext == "jpeg") {
        $gifname = substr($item, 0, -strlen($ext)) . "gif";
        echo "Exporting $item to $gifname\n";
        convertImage($item, $gifname);