function extract_mean_colour($image, $ref)
{
    # for image $image, calculate the mean colour and update this to the image_red, image_green, image_blue tables
    # in the resources table.
    # Also - we insert the height and width of the thumbnail at this stage as all information is available and we
    # are already performing an update on the resource record.
    $width = imagesx($image);
    $height = imagesy($image);
    $totalred = 0;
    $totalgreen = 0;
    $totalblue = 0;
    $total = 0;
    for ($y = 0; $y < 20; $y++) {
        for ($x = 0; $x < 20; $x++) {
            $rgb = imagecolorat($image, $x * ($width / 20), $y * ($height / 20));
            $red = $rgb >> 16 & 0xff;
            $green = $rgb >> 8 & 0xff;
            $blue = $rgb & 0xff;
            # calculate deltas (remove brightness factor)
            $cmax = max($red, $green, $blue);
            $cmin = min($red, $green, $blue);
            if ($cmax == $cmin) {
                $cmax = 10;
                $cmin = 0;
            }
            # avoid division errors
            if (abs($cmax - $cmin) >= 20) {
                $red = floor(($red - $cmin) / ($cmax - $cmin) * 1000);
                $green = floor(($green - $cmin) / ($cmax - $cmin) * 1000);
                $blue = floor(($blue - $cmin) / ($cmax - $cmin) * 1000);
                $total++;
                $totalred += $red;
                $totalgreen += $green;
                $totalblue += $blue;
            }
        }
    }
    if ($total == 0) {
        $total = 1;
    }
    $totalred = floor($totalred / $total);
    $totalgreen = floor($totalgreen / $total);
    $totalblue = floor($totalblue / $total);
    $colkey = get_colour_key($image);
    update_portrait_landscape_field($ref, $image);
    sql_query("update resource set image_red='{$totalred}', image_green='{$totalgreen}', image_blue='{$totalblue}',colour_key='{$colkey}',thumb_width='{$width}', thumb_height='{$height}' where ref='{$ref}'");
}
<?php

# This script is for updating the $portrait_landscape_field
include "../../include/db.php";
include "../../include/authenticate.php";
if (!checkperm("a")) {
    exit("Permission denied");
}
include "../../include/general.php";
include "../../include/resource_functions.php";
include "../../include/image_processing.php";
set_time_limit(60 * 60 * 40);
echo "Updating portrait_landscape_field (field {$portrait_landscape_field})...";
$rd = sql_query("select ref,file_extension from resource where has_image=1 ");
for ($n = 0; $n < count($rd); $n++) {
    $ref = $rd[$n]['ref'];
    echo "<br />" . $ref;
    update_portrait_landscape_field($ref);
    flush();
    ob_flush();
}
echo "...done.";