/**
  * Convert an image. Returns TRUE when successfull, FALSE if image is
  * not a truecolor image.
  *
  * @param   img.Image image
  * @return  bool
  * @throws  img.ImagingException
  */
 public function convert($image)
 {
     if (!imageistruecolor($image->handle)) {
         return false;
     }
     $tmp = Image::create($image->getWidth(), $image->getHeight(), IMG_TRUECOLOR);
     $tmp->copyFrom($image);
     imagetruecolortopalette($image->handle, $this->dither, $this->ncolors);
     imagecolormatch($tmp->handle, $image->handle);
     unset($tmp);
     return true;
 }
 function asPalette($nColors = 255, $dither = null, $matchPalette = true)
 {
     $nColors = intval($nColors);
     if ($nColors < 1) {
         $nColors = 1;
     } elseif ($nColors > 255) {
         $nColors = 255;
     }
     if ($dither === null) {
         $dither = $this->isTransparent();
     }
     $temp = $this->copy();
     imagetruecolortopalette($temp->handle, $dither, $nColors);
     if ($matchPalette == true) {
         imagecolormatch($this->handle, $temp->handle);
     }
     if ($this->isTransparent()) {
         $trgb = $this->getTransparentColorRGB();
         $tci = $temp->getClosestColor($trgb);
         $temp->setTransparentColor($tci);
     }
     $temp->releaseHandle();
     return new wiPaletteImage($temp->handle);
 }
<?php

$ima = imagecreatetruecolor(110, 20);
$background_color = imagecolorallocate($ima, 0, 0, 0);
$imb = imagecreatetruecolor(110, 20);
$background_color = imagecolorallocate($imb, 0, 0, 100);
var_dump(imagecolormatch($ima, $imb));
function image_aplatir($im, $format = 'jpg', $coul = '000000', $qualite = null, $transparence = false)
{
    if ($qualite === null) {
        if ($format == 'jpg') {
            $qualite = _IMG_GD_QUALITE;
        } elseif ($format == 'png') {
            $qualite = 0;
        } else {
            $qualite = 128;
        }
    }
    $fonction = array('image_aplatir', func_get_args());
    $image = _image_valeurs_trans($im, "aplatir-{$format}-{$coul}-{$qualite}-{$transparence}", $format, $fonction);
    if (!$image) {
        return "";
    }
    include_spip('inc/filtres');
    $couleurs = _couleur_hex_to_dec($coul);
    $dr = $couleurs["red"];
    $dv = $couleurs["green"];
    $db = $couleurs["blue"];
    $x_i = $image["largeur"];
    $y_i = $image["hauteur"];
    $im = $image["fichier"];
    $dest = $image["fichier_dest"];
    $creer = $image["creer"];
    if ($creer) {
        $im = @$image["fonction_imagecreatefrom"]($im);
        imagepalettetotruecolor($im);
        $im_ = imagecreatetruecolor($x_i, $y_i);
        if ($image["format_source"] == "gif" and function_exists('ImageCopyResampled')) {
            // Si un GIF est transparent,
            // fabriquer un PNG transparent
            // Conserver la transparence
            @imagealphablending($im_, false);
            @imagesavealpha($im_, true);
            if (function_exists("imageAntiAlias")) {
                imageAntiAlias($im_, true);
            }
            @ImageCopyResampled($im_, $im, 0, 0, 0, 0, $x_i, $y_i, $x_i, $y_i);
            imagedestroy($im);
            $im = $im_;
        }
        // allouer la couleur de fond
        if ($transparence) {
            @imagealphablending($im_, false);
            @imagesavealpha($im_, true);
            $color_t = imagecolorallocatealpha($im_, $dr, $dv, $db, 127);
        } else {
            $color_t = ImageColorAllocate($im_, $dr, $dv, $db);
        }
        imagefill($im_, 0, 0, $color_t);
        //??
        //$dist = abs($trait);
        $transp_x = false;
        if ($image["format_source"] == "jpg") {
            $im_ =& $im;
        } else {
            for ($x = 0; $x < $x_i; $x++) {
                for ($y = 0; $y < $y_i; $y++) {
                    $rgb = ImageColorAt($im, $x, $y);
                    $a = $rgb >> 24 & 0xff;
                    $r = $rgb >> 16 & 0xff;
                    $g = $rgb >> 8 & 0xff;
                    $b = $rgb & 0xff;
                    $a = (127 - $a) / 127;
                    if ($a == 1) {
                        // Limiter calculs
                        $r = $r;
                        $g = $g;
                        $b = $b;
                    } else {
                        if ($a == 0) {
                            // Limiter calculs
                            $r = $dr;
                            $g = $dv;
                            $b = $db;
                            $transp_x = $x;
                            // Memoriser un point transparent
                            $transp_y = $y;
                        } else {
                            $r = round($a * $r + $dr * (1 - $a));
                            $g = round($a * $g + $dv * (1 - $a));
                            $b = round($a * $b + $db * (1 - $a));
                        }
                    }
                    $a = (1 - $a) * 127;
                    $color = ImageColorAllocateAlpha($im_, $r, $g, $b, $a);
                    imagesetpixel($im_, $x, $y, $color);
                }
            }
        }
        // passer en palette si besoin
        if ($format == 'gif' or $format == 'png' and $qualite !== 0) {
            // creer l'image finale a palette
            // (on recycle l'image initiale si possible, sinon on en recree une)
            if ($im === $im_) {
                $im = imagecreatetruecolor($x_i, $y_i);
            }
            @imagetruecolortopalette($im, true, $qualite);
            //$im = imagecreate($x_i, $y_i);
            // copier l'image true color vers la palette
            imagecopy($im, $im_, 0, 0, 0, 0, $x_i, $y_i);
            // matcher les couleurs au mieux par rapport a l'image initiale
            // si la fonction est disponible (php>=4.3)
            if (function_exists('imagecolormatch')) {
                @imagecolormatch($im_, $im);
            }
            if ($format == 'gif' && $transparence && $transp_x) {
                $color_t = ImagecolorAt($im, $transp_x, $transp_y);
                if ($format == "gif" && $transparence) {
                    @imagecolortransparent($im, $color_t);
                }
            }
            // produire le resultat
            _image_gd_output($im, $image, $qualite);
        } else {
            _image_gd_output($im_, $image, $qualite);
        }
        if ($im !== $im_) {
            imagedestroy($im);
        }
        imagedestroy($im_);
    }
    return _image_ecrire_tag($image, array('src' => $dest));
}
Exemple #5
0
<?php

$im = imagecreatetruecolor(5, 5);
$im2 = imagecreate(5, 5);
imagecolormatch($im, $im2);
echo "ok\n";
imagedestroy($im);
Exemple #6
0
 public function get($type = 'png', $interlace = false, $quality = NULL, $filter = PNG_ALL_FILTERS)
 {
     $type = strtolower($type);
     if ($interlace === true) {
         imageinterlace($this->image, 1);
     }
     ob_start();
     switch ($type) {
         case 'png':
             $quality = $quality === NULL ? 9 : max(0, min(9, (int) $quality));
             imagepng($this->image, NULL, $quality, $filter);
             break;
         case 'jpeg':
             $quality = $quality === NULL ? 100 : max(0, min(100, (int) $quality));
             imagejpeg($this->image, NULL, $quality);
             break;
         case 'gif':
             $quality = $quality === NULL ? 255 : max(0, min(255, (int) $quality));
             $temp = imagecreatetruecolor($this->width, $this->height);
             imagecopy($temp, $this->image, 0, 0, 0, 0, $this->width, $this->height);
             imagetruecolortopalette($temp, false, $quality);
             imagecolormatch($this->image, $temp);
             imagegif($temp);
             break;
     }
     return trim(ob_get_clean());
 }
Exemple #7
0
 public function match($sourceImage = '')
 {
     if (!is_resource($sourceImage)) {
         return Error::set(lang('Error', 'resourceParameter', '1.(sourceImage)'));
     }
     imagecolormatch($this->canvas, $sourceImage);
     return $this;
 }
 /**
  * @see WideImage_Image#asPalette($nColors, $dither, $matchPalette)
  */
 function asPalette($nColors = 255, $dither = null, $matchPalette = true)
 {
     $nColors = intval($nColors);
     if ($nColors < 1) {
         $nColors = 1;
     } elseif ($nColors > 255) {
         $nColors = 255;
     }
     if ($dither === null) {
         $dither = $this->isTransparent();
     }
     $temp = $this->copy();
     imagetruecolortopalette($temp->handle, $dither, $nColors);
     if ($matchPalette == true && function_exists('imagecolormatch')) {
         imagecolormatch($this->handle, $temp->handle);
     }
     // The code below isn't working properly; it corrupts transparency on some palette->tc->palette conversions.
     // Why is this code here?
     /*
     			if ($this->isTransparent())
     			{
     				$trgb = $this->getTransparentColorRGB();
     				$tci = $temp->getClosestColor($trgb);
     				$temp->setTransparentColor($tci);
     			}
     			/**/
     $temp->releaseHandle();
     return new WideImage_PaletteImage($temp->handle);
 }
 public function ImageTrueColorToPalette2(&$image, $dither, $ncolors)
 {
     // http://www.php.net/manual/en/function.imagetruecolortopalette.php
     // zmorris at zsculpt dot com (17-Aug-2004 06:58)
     $width = imagesx($image);
     $height = imagesy($image);
     $image_copy = imagecreatetruecolor($width, $height);
     //imagecopymerge($image_copy, $image, 0, 0, 0, 0, $width, $height, 100);
     imagecopy($image_copy, $image, 0, 0, 0, 0, $width, $height);
     imagetruecolortopalette($image, $dither, $ncolors);
     imagecolormatch($image_copy, $image);
     imagedestroy($image_copy);
     return true;
 }
 function generate_thumbnails($source, $targets_and_constraints, $target_format, $thumbnail_quality)
 {
     $files_created_in_operation = array();
     list($width, $height) = getimagesize($source);
     $ok = false;
     if ($width > 0) {
         $pixel_size_buffer = 1.25;
         $max_bytes = $comicpress_manager->convert_short_size_string_to_bytes(ini_get('memory_limit'));
         if ($max_bytes > 0) {
             $max_thumb_size = 0;
             foreach ($targets_and_constraints as $target_and_constraint) {
                 list($target, $constraint) = $target_and_constraint;
                 $width_to_use = $constraint['width'];
                 $archive_comic_height = (int) ($width_to_use * $height / $width);
                 $max_thumb_size = max($width_to_use * $archive_comic_height * 4, $max_thumb_size);
             }
             $input_image_size = $width * $height * 4;
             if (strtolower(pathinfo($input, PATHINFO_EXTENSION)) == "gif") {
                 $input_image_size *= 2;
             }
             $recommended_size = ($input_image_size + $max_thumb_size) * $pixel_size_buffer;
             if (function_exists('memory_get_usage')) {
                 $recommended_size += memory_get_usage();
             }
             if ($recommended_size > $max_bytes) {
                 $comicpress_manager->warnings[] = sprintf(__("<strong>You don't have enough memory available to PHP and GD to process this file.</strong> You should <strong>set your PHP <tt>memory_size</tt></strong> to at least <strong><tt>%sM</tt></strong> and try again. For more information, read the ComicPress Manager FAQ.", 'comicpress-manager'), (int) ($recommended_size / (1024 * 1024)));
                 return false;
             }
         }
         foreach ($targets_and_constraints as $target_and_constraint) {
             list($target, $constraint) = $target_and_constraint;
             $width_to_use = $constraint['width'];
             $archive_comic_height = (int) ($width_to_use * $height / $width);
             $pathinfo = pathinfo($source);
             $thumb_image = imagecreatetruecolor($width_to_use, $archive_comic_height);
             imagealphablending($thumb_image, true);
             switch (strtolower($pathinfo['extension'])) {
                 case "jpg":
                 case "jpeg":
                     $comic_image = imagecreatefromjpeg($source);
                     break;
                 case "gif":
                     $is_gif = true;
                     $temp_comic_image = imagecreatefromgif($source);
                     list($width, $height) = getimagesize($input);
                     $comic_image = imagecreatetruecolor($width, $height);
                     imagecopy($comic_image, $temp_comic_image, 0, 0, 0, 0, $width, $height);
                     imagedestroy($temp_comic_image);
                     break;
                 case "png":
                     $comic_image = imagecreatefrompng($source);
                     break;
                 default:
                     return false;
             }
             imagealphablending($comic_image, true);
             if ($is_palette = !imageistruecolor($comic_image)) {
                 $number_of_colors = imagecolorstotal($comic_image);
             }
             imagecopyresampled($thumb_image, $comic_image, 0, 0, 0, 0, $width_to_use, $archive_comic_height, $width, $height);
             $ok = true;
             @touch($target);
             if (file_exists($target)) {
                 @unlink($target);
                 switch (strtolower($target_format)) {
                     case "jpg":
                     case "jpeg":
                         if (imagetypes() & IMG_JPG) {
                             @imagejpeg($thumb_image, $target, $comicpress_manager->get_cpm_option("cpm-thumbnail-quality"));
                         } else {
                             return false;
                         }
                         break;
                     case "gif":
                         if (imagetypes() & IMG_GIF) {
                             if (function_exists('imagecolormatch')) {
                                 $temp_comic_image = imagecreate($width_to_use, $archive_comic_height);
                                 imagecopymerge($temp_comic_image, $thumb_image, 0, 0, 0, 0, $width_to_use, $archive_comic_height, 100);
                                 imagecolormatch($thumb_image, $temp_comic_image);
                                 @imagegif($temp_comic_image, $target);
                                 imagedestroy($temp_comic_image);
                             } else {
                                 @imagegif($thumb_image, $target);
                             }
                         } else {
                             return false;
                         }
                         break;
                     case "png":
                         if (imagetypes() & IMG_PNG) {
                             if ($is_palette) {
                                 imagetruecolortopalette($thumb_image, true, $number_of_colors);
                             }
                             @imagepng($thumb_image, $target, 9);
                         } else {
                             return false;
                         }
                         break;
                     default:
                         return false;
                 }
             }
             if (!file_exists($target)) {
                 $ok = false;
             } else {
                 @chmod($target, CPM_FILE_UPLOAD_CHMOD);
                 $files_created_in_operation[] = $target;
             }
             imagedestroy($comic_image);
             imagedestroy($thumb_image);
         }
     }
     return $ok ? $files_created_in_operation : false;
 }
 public function match($sourceImage) : InternalGD
 {
     if (!is_resource($sourceImage)) {
         throw new InvalidArgumentException('Error', 'resourceParameter', '1.($sourceImage)');
     }
     imagecolormatch($this->canvas, $sourceImage);
     return $this;
 }
 /**
  * @see GDImage_Image#asPalette($nColors, $dither, $matchPalette)
  */
 function asPalette($nColors = 255, $dither = null, $matchPalette = true)
 {
     $nColors = intval($nColors);
     if ($nColors < 1) {
         $nColors = 1;
     } elseif ($nColors > 255) {
         $nColors = 255;
     }
     if ($dither === null) {
         $dither = $this->isTransparent();
     }
     $temp = $this->copy();
     imagetruecolortopalette($temp->handle, $dither, $nColors);
     if ($matchPalette == true && function_exists('imagecolormatch')) {
         imagecolormatch($this->handle, $temp->handle);
     }
     $temp->releaseHandle();
     return new GDImage_PaletteImage($temp->handle);
 }
<?php

$ima = imagecreatetruecolor(110, 20);
$background_color = imagecolorallocate($ima, 0, 0, 0);
var_dump(imagecolormatch($ima));
/**
 * Write a thumbnail image to the thumbnail folders.
 * @param string $input The input image filename.
 * @param string $target_filename The filename for the thumbnails.
 * @param boolean $do_rebuild If true, force rebuilding thumbnails.
 * @return mixed True if successful, false if not, null if unable to write.
 */
function cpm_write_thumbnail($input, $target_filename, $do_rebuild = false)
{
    global $cpm_config;
    $target_format = pathinfo($target_filename, PATHINFO_EXTENSION);
    $files_created_in_operation = array();
    $write_targets = array();
    foreach ($cpm_config->separate_thumbs_folder_defined as $type => $value) {
        if ($value) {
            if ($cpm_config->thumbs_folder_writable[$type]) {
                if (cpm_option("cpm-{$type}-generate-thumbnails") == 1) {
                    $converted_target_filename = preg_replace('#\\.[^\\.]+$#', '', $target_filename) . '.' . $target_format;
                    $target = CPM_DOCUMENT_ROOT . '/' . $cpm_config->properties[$type . "_comic_folder"];
                    if (($subdir = cpm_get_subcomic_directory()) !== false) {
                        $target .= '/' . $subdir;
                    }
                    $target .= '/' . $converted_target_filename;
                    if (!in_array($target, $write_targets)) {
                        $write_targets[$type] = $target;
                    }
                }
            }
        }
    }
    if (count($write_targets) > 0) {
        if (!$do_rebuild) {
            if (file_exists($input)) {
                if (file_exists($target)) {
                    if (filemtime($input) > filemtime($target)) {
                        $do_rebuild = true;
                    }
                } else {
                    $do_rebuild = true;
                }
            }
        }
        if ($do_rebuild) {
            switch ($cpm_config->get_scale_method()) {
                case CPM_SCALE_NONE:
                    return null;
                case CPM_SCALE_IMAGEMAGICK:
                    $original_size = getimagesize($input);
                    $unique_colors = exec("identify -format '%k' '{$input}'");
                    if (empty($unique_colors)) {
                        $unique_colors = 256;
                    }
                    $ok = true;
                    foreach ($write_targets as $type => $target) {
                        $width_to_use = isset($cpm_config->properties["{$type}_comic_width"]) ? $cpm_config->properties["{$type}_comic_width"] : $cpm_config->properties['archive_comic_width'];
                        if ($width_to_use < $original_size[0]) {
                            $command = array("convert", "\"{$input}\"", "-filter Lanczos", "-resize " . $width_to_use . "x");
                            $im_target = $target;
                            switch (strtolower($target_format)) {
                                case "jpg":
                                case "jpeg":
                                    $command[] = "-quality " . cpm_option("cpm-thumbnail-quality");
                                    break;
                                case "gif":
                                    $command[] = "-colors {$unique_colors}";
                                    break;
                                case "png":
                                    if ($unique_colors <= 256) {
                                        $im_target = "png8:{$im_target}";
                                        $command[] = "-colors {$unique_colors}";
                                    }
                                    $command[] = "-quality 100";
                                    break;
                                default:
                            }
                            $command[] = "\"{$im_target}\"";
                            $convert_to_thumb = escapeshellcmd(implode(" ", $command));
                            exec($convert_to_thumb);
                            if (!file_exists($target)) {
                                $ok = false;
                            } else {
                                @chmod($target, CPM_FILE_UPLOAD_CHMOD);
                                $files_created_in_operation[] = $target;
                            }
                        } else {
                            copy($input, $target);
                        }
                    }
                    return $ok ? $files_created_in_operation : false;
                case CPM_SCALE_GD:
                    list($width, $height) = getimagesize($input);
                    if ($width > 0) {
                        $pixel_size_buffer = 1.25;
                        $max_bytes = cpm_short_size_string_to_bytes(ini_get('memory_limit'));
                        if ($max_bytes > 0) {
                            $max_thumb_size = 0;
                            foreach ($write_targets as $type => $target) {
                                $width_to_use = isset($cpm_config->properties["{$type}_comic_width"]) ? $cpm_config->properties["{$type}_comic_width"] : $cpm_config->properties['archive_comic_width'];
                                $archive_comic_height = (int) ($width_to_use * $height / $width);
                                $max_thumb_size = max($width_to_use * $archive_comic_height * 4, $max_thumb_size);
                            }
                            $input_image_size = $width * $height * 4;
                            if (strtolower(pathinfo($input, PATHINFO_EXTENSION)) == "gif") {
                                $input_image_size *= 2;
                            }
                            $recommended_size = ($input_image_size + $max_thumb_size) * $pixel_size_buffer;
                            if (function_exists('memory_get_usage')) {
                                $recommended_size += memory_get_usage();
                            }
                            if ($recommended_size > $max_bytes) {
                                $cpm_config->warnings[] = sprintf(__("<strong>You don't have enough memory available to PHP and GD to process this file.</strong> You should <strong>set your PHP <tt>memory_size</tt></strong> to at least <strong><tt>%sM</tt></strong> and try again. For more information, read the ComicPress Manager FAQ.", 'comicpress-manager'), (int) ($recommended_size / (1024 * 1024)));
                                return false;
                            }
                        }
                        foreach ($write_targets as $type => $target) {
                            $width_to_use = isset($cpm_config->properties["{$type}_comic_width"]) ? $cpm_config->properties["{$type}_comic_width"] : $cpm_config->properties['archive_comic_width'];
                            if ($width_to_use < $width) {
                                $archive_comic_height = (int) ($width_to_use * $height / $width);
                                $pathinfo = pathinfo($input);
                                $thumb_image = imagecreatetruecolor($width_to_use, $archive_comic_height);
                                imagealphablending($thumb_image, true);
                                switch (strtolower($pathinfo['extension'])) {
                                    case "jpg":
                                    case "jpeg":
                                        $comic_image = imagecreatefromjpeg($input);
                                        break;
                                    case "gif":
                                        $is_gif = true;
                                        $temp_comic_image = imagecreatefromgif($input);
                                        list($width, $height) = getimagesize($input);
                                        $comic_image = imagecreatetruecolor($width, $height);
                                        imagecopy($comic_image, $temp_comic_image, 0, 0, 0, 0, $width, $height);
                                        imagedestroy($temp_comic_image);
                                        break;
                                    case "png":
                                        $comic_image = imagecreatefrompng($input);
                                        break;
                                    default:
                                        return false;
                                }
                                imagealphablending($comic_image, true);
                                if ($is_palette = !imageistruecolor($comic_image)) {
                                    $number_of_colors = imagecolorstotal($comic_image);
                                }
                                imagecopyresampled($thumb_image, $comic_image, 0, 0, 0, 0, $width_to_use, $archive_comic_height, $width, $height);
                                $ok = true;
                                @touch($target);
                                if (file_exists($target)) {
                                    @unlink($target);
                                    switch (strtolower($target_format)) {
                                        case "jpg":
                                        case "jpeg":
                                            if (imagetypes() & IMG_JPG) {
                                                @imagejpeg($thumb_image, $target, cpm_option("cpm-thumbnail-quality"));
                                            } else {
                                                return false;
                                            }
                                            break;
                                        case "gif":
                                            if (imagetypes() & IMG_GIF) {
                                                if (function_exists('imagecolormatch')) {
                                                    $temp_comic_image = imagecreate($width_to_use, $archive_comic_height);
                                                    imagecopymerge($temp_comic_image, $thumb_image, 0, 0, 0, 0, $width_to_use, $archive_comic_height, 100);
                                                    imagecolormatch($thumb_image, $temp_comic_image);
                                                    @imagegif($temp_comic_image, $target);
                                                    imagedestroy($temp_comic_image);
                                                } else {
                                                    @imagegif($thumb_image, $target);
                                                }
                                            } else {
                                                return false;
                                            }
                                            break;
                                        case "png":
                                            if (imagetypes() & IMG_PNG) {
                                                if ($is_palette) {
                                                    imagetruecolortopalette($thumb_image, true, $number_of_colors);
                                                }
                                                @imagepng($thumb_image, $target, 9);
                                            } else {
                                                return false;
                                            }
                                            break;
                                        default:
                                            return false;
                                    }
                                }
                            } else {
                                copy($input, $target);
                            }
                            if (!file_exists($target)) {
                                $ok = false;
                            } else {
                                @chmod($target, CPM_FILE_UPLOAD_CHMOD);
                                $files_created_in_operation[] = $target;
                            }
                            imagedestroy($comic_image);
                            imagedestroy($thumb_image);
                        }
                    } else {
                        $ok = false;
                    }
                    return $ok ? $files_created_in_operation : false;
            }
        }
    }
    return null;
}
Exemple #15
0
 /**
  * Resize an image
  * @param string
  * @param integer
  * @param integer
  * @param string
  * @param string
  * @return string
  */
 protected function getImage($image, $width, $height, $mode = '', $target = null)
 {
     if (!strlen($image)) {
         return null;
     }
     $image = urldecode($image);
     // Check whether the file exists
     if (!file_exists(TL_ROOT . '/' . $image)) {
         $this->log('Image "' . $image . '" could not be found', 'Controller getImage()', TL_ERROR);
         return null;
     }
     $objFile = new File($image);
     $arrAllowedTypes = trimsplit(',', strtolower($GLOBALS['TL_CONFIG']['validImageTypes']));
     // Check the file type
     if (!in_array($objFile->extension, $arrAllowedTypes)) {
         $this->log('Image type "' . $objFile->extension . '" was not allowed to be processed', 'Controller getImage()', TL_ERROR);
         return null;
     }
     // No resizing required
     if ($objFile->width == $width && $objFile->height == $height) {
         return $image;
     }
     $strCacheName = 'system/html/' . $objFile->filename . '-' . substr(md5('-w' . $width . '-h' . $height . '-' . $image . '-' . $mode . '-' . $objFile->mtime), 0, 8) . '.' . $objFile->extension;
     // Return the path of the new image if it exists already
     if (file_exists(TL_ROOT . '/' . $strCacheName)) {
         return $strCacheName;
     }
     // HOOK: add custom logic
     if (isset($GLOBALS['TL_HOOKS']['getImage']) && is_array($GLOBALS['TL_HOOKS']['getImage'])) {
         foreach ($GLOBALS['TL_HOOKS']['getImage'] as $callback) {
             $this->import($callback[0]);
             $return = $this->{$callback}[0]->{$callback}[1]($image, $width, $height, $mode, $strCacheName, $objFile, $target);
             if (is_string($return)) {
                 return $return;
             }
         }
     }
     // Return the path to the original image if the GDlib cannot handle it
     if (!extension_loaded('gd') || !$objFile->isGdImage || $objFile->width > $GLOBALS['TL_CONFIG']['gdMaxImgWidth'] || $objFile->height > $GLOBALS['TL_CONFIG']['gdMaxImgHeight'] || !$width && !$height || $width > 1200 || $height > 1200) {
         return $image;
     }
     $intPositionX = 0;
     $intPositionY = 0;
     $intWidth = $width;
     $intHeight = $height;
     // Mode-specific changes
     if ($intWidth && $intHeight) {
         switch ($mode) {
             case 'proportional':
                 if ($objFile->width >= $objFile->height) {
                     unset($height, $intHeight);
                 } else {
                     unset($width, $intWidth);
                 }
                 break;
             case 'box':
                 if (ceil($objFile->height * $width / $objFile->width) <= $intHeight) {
                     unset($height, $intHeight);
                 } else {
                     unset($width, $intWidth);
                 }
                 break;
         }
     }
     // Resize width and height and crop the image if necessary
     if ($intWidth && $intHeight) {
         if ($intWidth * $objFile->height != $intHeight * $objFile->width) {
             $intWidth = ceil($objFile->width * $height / $objFile->height);
             $intPositionX = -intval(($intWidth - $width) / 2);
             if ($intWidth < $width) {
                 $intWidth = $width;
                 $intHeight = ceil($objFile->height * $width / $objFile->width);
                 $intPositionX = 0;
                 $intPositionY = -intval(($intHeight - $height) / 2);
             }
         }
         $strNewImage = imagecreatetruecolor($width, $height);
     } elseif ($intWidth) {
         $intHeight = ceil($objFile->height * $width / $objFile->width);
         $strNewImage = imagecreatetruecolor($intWidth, $intHeight);
     } elseif ($intHeight) {
         $intWidth = ceil($objFile->width * $height / $objFile->height);
         $strNewImage = imagecreatetruecolor($intWidth, $intHeight);
     }
     $arrGdinfo = gd_info();
     $strGdVersion = preg_replace('/[^0-9\\.]+/', '', $arrGdinfo['GD Version']);
     switch ($objFile->extension) {
         case 'gif':
             if ($arrGdinfo['GIF Read Support']) {
                 $strSourceImage = imagecreatefromgif(TL_ROOT . '/' . $image);
                 $intTranspIndex = imagecolortransparent($strSourceImage);
                 // Handle transparency
                 if ($intTranspIndex >= 0 && $intTranspIndex < imagecolorstotal($strSourceImage)) {
                     $arrColor = imagecolorsforindex($strSourceImage, $intTranspIndex);
                     $intTranspIndex = imagecolorallocate($strNewImage, $arrColor['red'], $arrColor['green'], $arrColor['blue']);
                     imagefill($strNewImage, 0, 0, $intTranspIndex);
                     imagecolortransparent($strNewImage, $intTranspIndex);
                 }
             }
             break;
         case 'jpg':
         case 'jpeg':
             if ($arrGdinfo['JPG Support'] || $arrGdinfo['JPEG Support']) {
                 $strSourceImage = imagecreatefromjpeg(TL_ROOT . '/' . $image);
             }
             break;
         case 'png':
             if ($arrGdinfo['PNG Support']) {
                 $strSourceImage = imagecreatefrompng(TL_ROOT . '/' . $image);
                 // Handle transparency (GDlib >= 2.0 required)
                 if (version_compare($strGdVersion, '2.0', '>=')) {
                     imagealphablending($strNewImage, false);
                     $intTranspIndex = imagecolorallocatealpha($strNewImage, 0, 0, 0, 127);
                     imagefill($strNewImage, 0, 0, $intTranspIndex);
                     imagesavealpha($strNewImage, true);
                 }
             }
             break;
     }
     // The new image could not be created
     if (!$strSourceImage) {
         $this->log('Image "' . $image . '" could not be processed', 'Controller getImage()', TL_ERROR);
         return null;
     }
     imagecopyresampled($strNewImage, $strSourceImage, $intPositionX, $intPositionY, 0, 0, $intWidth, $intHeight, $objFile->width, $objFile->height);
     // Fallback to PNG if GIF ist not supported
     if ($objFile->extension == 'gif' && !$arrGdinfo['GIF Create Support']) {
         $objFile->extension = 'png';
     }
     // Create the new image
     switch ($objFile->extension) {
         case 'gif':
             imagegif($strNewImage, TL_ROOT . '/' . $strCacheName);
             break;
         case 'jpg':
         case 'jpeg':
             imagejpeg($strNewImage, TL_ROOT . '/' . $strCacheName, !$GLOBALS['TL_CONFIG']['jpgQuality'] ? 80 : $GLOBALS['TL_CONFIG']['jpgQuality']);
             break;
         case 'png':
             // Optimize non-truecolor images (see #2426)
             if (version_compare($strGdVersion, '2.0', '>=') && function_exists('imagecolormatch') && !imageistruecolor($strSourceImage)) {
                 // TODO: make it work with transparent images, too
                 if (imagecolortransparent($strSourceImage) == -1) {
                     $intColors = imagecolorstotal($strSourceImage);
                     // Convert to a palette image
                     // @see http://www.php.net/manual/de/function.imagetruecolortopalette.php#44803
                     if ($intColors > 0 && $intColors < 256) {
                         $wi = imagesx($strNewImage);
                         $he = imagesy($strNewImage);
                         $ch = imagecreatetruecolor($wi, $he);
                         imagecopymerge($ch, $strNewImage, 0, 0, 0, 0, $wi, $he, 100);
                         imagetruecolortopalette($strNewImage, false, $intColors);
                         imagecolormatch($ch, $strNewImage);
                         imagedestroy($ch);
                     }
                 }
             }
             imagepng($strNewImage, TL_ROOT . '/' . $strCacheName);
             break;
     }
     // Destroy the temporary images
     imagedestroy($strSourceImage);
     imagedestroy($strNewImage);
     // Resize the original image
     if ($target) {
         $this->import('Files');
         $this->Files->rename($strCacheName, $target);
         return $target;
     }
     // Set the file permissions when the Safe Mode Hack is used
     if ($GLOBALS['TL_CONFIG']['useFTP']) {
         $this->import('Files');
         $this->Files->chmod($strCacheName, 0644);
     }
     // Return the path to new image
     return $strCacheName;
 }
Exemple #16
0
 /**
  * Resize an image and store the resized version in the assets/images folder
  *
  * @param string  $image  The image path
  * @param integer $width  The target width
  * @param integer $height The target height
  * @param string  $mode   The resize mode
  * @param string  $target An optional target path
  * @param boolean $force  Override existing target images
  *
  * @return string|null The path of the resized image or null
  */
 public static function get($image, $width, $height, $mode = '', $target = null, $force = false)
 {
     if ($image == '') {
         return null;
     }
     $image = rawurldecode($image);
     // Check whether the file exists
     if (!is_file(TL_ROOT . '/' . $image)) {
         \System::log('Image "' . $image . '" could not be found', __METHOD__, TL_ERROR);
         return null;
     }
     $objFile = new \File($image, true);
     $arrAllowedTypes = trimsplit(',', strtolower(\Config::get('validImageTypes')));
     // Check the file type
     if (!in_array($objFile->extension, $arrAllowedTypes)) {
         \System::log('Image type "' . $objFile->extension . '" was not allowed to be processed', __METHOD__, TL_ERROR);
         return null;
     }
     // No resizing required
     if (($objFile->width == $width || !$width) && ($objFile->height == $height || !$height)) {
         // Return the target image (thanks to Tristan Lins) (see #4166)
         if ($target) {
             // Copy the source image if the target image does not exist or is older than the source image
             if (!file_exists(TL_ROOT . '/' . $target) || $objFile->mtime > filemtime(TL_ROOT . '/' . $target)) {
                 \Files::getInstance()->copy($image, $target);
             }
             return \System::urlEncode($target);
         }
         return \System::urlEncode($image);
     }
     // No mode given
     if ($mode == '') {
         // Backwards compatibility
         if ($width && $height) {
             $mode = 'center_top';
         } else {
             $mode = 'proportional';
         }
     }
     // Backwards compatibility
     if ($mode == 'crop') {
         $mode = 'center_center';
     }
     $strCacheKey = substr(md5('-w' . $width . '-h' . $height . '-' . $image . '-' . $mode . '-' . $objFile->mtime), 0, 8);
     $strCacheName = 'assets/images/' . substr($strCacheKey, -1) . '/' . $objFile->filename . '-' . $strCacheKey . '.' . $objFile->extension;
     // Check whether the image exists already
     if (!\Config::get('debugMode')) {
         // Custom target (thanks to Tristan Lins) (see #4166)
         if ($target && !$force) {
             if (file_exists(TL_ROOT . '/' . $target) && $objFile->mtime <= filemtime(TL_ROOT . '/' . $target)) {
                 return \System::urlEncode($target);
             }
         }
         // Regular cache file
         if (file_exists(TL_ROOT . '/' . $strCacheName)) {
             // Copy the cached file if it exists
             if ($target) {
                 \Files::getInstance()->copy($strCacheName, $target);
                 return \System::urlEncode($target);
             }
             return \System::urlEncode($strCacheName);
         }
     }
     // HOOK: add custom logic
     if (isset($GLOBALS['TL_HOOKS']['getImage']) && is_array($GLOBALS['TL_HOOKS']['getImage'])) {
         foreach ($GLOBALS['TL_HOOKS']['getImage'] as $callback) {
             $return = \System::importStatic($callback[0])->{$callback}[1]($image, $width, $height, $mode, $strCacheName, $objFile, $target);
             if (is_string($return)) {
                 return \System::urlEncode($return);
             }
         }
     }
     // Return the path to the original image if the GDlib cannot handle it
     if (!extension_loaded('gd') || !$objFile->isGdImage || $objFile->width > \Config::get('gdMaxImgWidth') || $objFile->height > \Config::get('gdMaxImgHeight') || !$width && !$height || $width > \Config::get('gdMaxImgWidth') || $height > \Config::get('gdMaxImgHeight')) {
         return \System::urlEncode($image);
     }
     $intPositionX = 0;
     $intPositionY = 0;
     $intWidth = $width;
     $intHeight = $height;
     // Mode-specific changes
     if ($intWidth && $intHeight) {
         switch ($mode) {
             case 'proportional':
                 if ($objFile->width >= $objFile->height) {
                     unset($height, $intHeight);
                 } else {
                     unset($width, $intWidth);
                 }
                 break;
             case 'box':
                 if (round($objFile->height * $width / $objFile->width) <= $intHeight) {
                     unset($height, $intHeight);
                 } else {
                     unset($width, $intWidth);
                 }
                 break;
         }
     }
     $strNewImage = null;
     $strSourceImage = null;
     // Resize width and height and crop the image if necessary
     if ($intWidth && $intHeight) {
         if ($intWidth * $objFile->height != $intHeight * $objFile->width) {
             $intWidth = max(round($objFile->width * $height / $objFile->height), 1);
             $intPositionX = -intval(($intWidth - $width) / 2);
             if ($intWidth < $width) {
                 $intWidth = $width;
                 $intHeight = max(round($objFile->height * $width / $objFile->width), 1);
                 $intPositionX = 0;
                 $intPositionY = -intval(($intHeight - $height) / 2);
             }
         }
         // Advanced crop modes
         switch ($mode) {
             case 'left_top':
                 $intPositionX = 0;
                 $intPositionY = 0;
                 break;
             case 'center_top':
                 $intPositionX = -intval(($intWidth - $width) / 2);
                 $intPositionY = 0;
                 break;
             case 'right_top':
                 $intPositionX = -intval($intWidth - $width);
                 $intPositionY = 0;
                 break;
             case 'left_center':
                 $intPositionX = 0;
                 $intPositionY = -intval(($intHeight - $height) / 2);
                 break;
             case 'center_center':
                 $intPositionX = -intval(($intWidth - $width) / 2);
                 $intPositionY = -intval(($intHeight - $height) / 2);
                 break;
             case 'right_center':
                 $intPositionX = -intval($intWidth - $width);
                 $intPositionY = -intval(($intHeight - $height) / 2);
                 break;
             case 'left_bottom':
                 $intPositionX = 0;
                 $intPositionY = -intval($intHeight - $height);
                 break;
             case 'center_bottom':
                 $intPositionX = -intval(($intWidth - $width) / 2);
                 $intPositionY = -intval($intHeight - $height);
                 break;
             case 'right_bottom':
                 $intPositionX = -intval($intWidth - $width);
                 $intPositionY = -intval($intHeight - $height);
                 break;
         }
         $strNewImage = imagecreatetruecolor($width, $height);
     } elseif ($intWidth) {
         $intHeight = max(round($objFile->height * $width / $objFile->width), 1);
         $strNewImage = imagecreatetruecolor($intWidth, $intHeight);
     } elseif ($intHeight) {
         $intWidth = max(round($objFile->width * $height / $objFile->height), 1);
         $strNewImage = imagecreatetruecolor($intWidth, $intHeight);
     }
     $arrGdinfo = gd_info();
     $strGdVersion = preg_replace('/[^0-9\\.]+/', '', $arrGdinfo['GD Version']);
     switch ($objFile->extension) {
         case 'gif':
             if ($arrGdinfo['GIF Read Support']) {
                 $strSourceImage = imagecreatefromgif(TL_ROOT . '/' . $image);
                 $intTranspIndex = imagecolortransparent($strSourceImage);
                 // Handle transparency
                 if ($intTranspIndex >= 0 && $intTranspIndex < imagecolorstotal($strSourceImage)) {
                     $arrColor = imagecolorsforindex($strSourceImage, $intTranspIndex);
                     $intTranspIndex = imagecolorallocate($strNewImage, $arrColor['red'], $arrColor['green'], $arrColor['blue']);
                     imagefill($strNewImage, 0, 0, $intTranspIndex);
                     imagecolortransparent($strNewImage, $intTranspIndex);
                 }
             }
             break;
         case 'jpg':
         case 'jpeg':
             if ($arrGdinfo['JPG Support'] || $arrGdinfo['JPEG Support']) {
                 $strSourceImage = imagecreatefromjpeg(TL_ROOT . '/' . $image);
             }
             break;
         case 'png':
             if ($arrGdinfo['PNG Support']) {
                 $strSourceImage = imagecreatefrompng(TL_ROOT . '/' . $image);
                 // Handle transparency (GDlib >= 2.0 required)
                 if (version_compare($strGdVersion, '2.0', '>=')) {
                     imagealphablending($strNewImage, false);
                     $intTranspIndex = imagecolorallocatealpha($strNewImage, 0, 0, 0, 127);
                     imagefill($strNewImage, 0, 0, $intTranspIndex);
                     imagesavealpha($strNewImage, true);
                 }
             }
             break;
     }
     // The new image could not be created
     if (!$strSourceImage) {
         imagedestroy($strNewImage);
         \System::log('Image "' . $image . '" could not be processed', __METHOD__, TL_ERROR);
         return null;
     }
     imageinterlace($strNewImage, 1);
     // see #6529
     imagecopyresampled($strNewImage, $strSourceImage, $intPositionX, $intPositionY, 0, 0, $intWidth, $intHeight, $objFile->width, $objFile->height);
     // Fallback to PNG if GIF ist not supported
     if ($objFile->extension == 'gif' && !$arrGdinfo['GIF Create Support']) {
         $objFile->extension = 'png';
     }
     // Create the new image
     switch ($objFile->extension) {
         case 'gif':
             imagegif($strNewImage, TL_ROOT . '/' . $strCacheName);
             break;
         case 'jpg':
         case 'jpeg':
             imagejpeg($strNewImage, TL_ROOT . '/' . $strCacheName, \Config::get('jpgQuality') ?: 80);
             break;
         case 'png':
             // Optimize non-truecolor images (see #2426)
             if (version_compare($strGdVersion, '2.0', '>=') && function_exists('imagecolormatch') && !imageistruecolor($strSourceImage)) {
                 // TODO: make it work with transparent images, too
                 if (imagecolortransparent($strSourceImage) == -1) {
                     $intColors = imagecolorstotal($strSourceImage);
                     // Convert to a palette image
                     // @see http://www.php.net/manual/de/function.imagetruecolortopalette.php#44803
                     if ($intColors > 0 && $intColors < 256) {
                         $wi = imagesx($strNewImage);
                         $he = imagesy($strNewImage);
                         $ch = imagecreatetruecolor($wi, $he);
                         imagecopymerge($ch, $strNewImage, 0, 0, 0, 0, $wi, $he, 100);
                         imagetruecolortopalette($strNewImage, false, $intColors);
                         imagecolormatch($ch, $strNewImage);
                         imagedestroy($ch);
                     }
                 }
             }
             imagepng($strNewImage, TL_ROOT . '/' . $strCacheName);
             break;
     }
     // Destroy the temporary images
     imagedestroy($strSourceImage);
     imagedestroy($strNewImage);
     // Resize the original image
     if ($target) {
         \Files::getInstance()->copy($strCacheName, $target);
         return \System::urlEncode($target);
     }
     // Set the file permissions when the Safe Mode Hack is used
     if (\Config::get('useFTP')) {
         \Files::getInstance()->chmod($strCacheName, \Config::get('defaultFileChmod'));
     }
     // Return the path to new image
     return \System::urlEncode($strCacheName);
 }
 /**
  * Crop the image and return the file path
  * @param string
  * @param integer
  * @param integer
  * @return string
  */
 protected function cropImage($strFile, $intPositionX, $intPositionY)
 {
     $strThumbnail = $this->getThumbnailPath($strFile);
     list($intWidth, $intHeight) = $this->getThumbnailDimensions($strFile);
     // Resize to thumbnail size first
     \Image::resize($strFile, $intWidth, $intHeight, 'proportional');
     $arrGdinfo = gd_info();
     $strGdVersion = preg_replace('/[^0-9\\.]+/', '', $arrGdinfo['GD Version']);
     $strNewImage = imagecreatetruecolor($this->arrAvatarSize[0], $this->arrAvatarSize[1]);
     $strExtension = strtolower(pathinfo($strFile, PATHINFO_EXTENSION));
     switch ($strExtension) {
         case 'gif':
             if ($arrGdinfo['GIF Read Support']) {
                 $strSourceImage = imagecreatefromgif(TL_ROOT . '/' . $strFile);
                 $intTranspIndex = imagecolortransparent($strSourceImage);
                 // Handle transparency
                 if ($intTranspIndex >= 0 && $intTranspIndex < imagecolorstotal($strSourceImage)) {
                     $arrColor = imagecolorsforindex($strSourceImage, $intTranspIndex);
                     $intTranspIndex = imagecolorallocate($strNewImage, $arrColor['red'], $arrColor['green'], $arrColor['blue']);
                     imagefill($strNewImage, 0, 0, $intTranspIndex);
                     imagecolortransparent($strNewImage, $intTranspIndex);
                 }
             }
             break;
         case 'jpg':
         case 'jpeg':
             if ($arrGdinfo['JPG Support'] || $arrGdinfo['JPEG Support']) {
                 $strSourceImage = imagecreatefromjpeg(TL_ROOT . '/' . $strFile);
             }
             break;
         case 'png':
             if ($arrGdinfo['PNG Support']) {
                 $strSourceImage = imagecreatefrompng(TL_ROOT . '/' . $strFile);
                 // Handle transparency (GDlib >= 2.0 required)
                 if (version_compare($strGdVersion, '2.0', '>=')) {
                     imagealphablending($strNewImage, false);
                     $intTranspIndex = imagecolorallocatealpha($strNewImage, 0, 0, 0, 127);
                     imagefill($strNewImage, 0, 0, $intTranspIndex);
                     imagesavealpha($strNewImage, true);
                 }
             }
             break;
     }
     // The new image could not be created
     if (!$strSourceImage) {
         imagedestroy($strNewImage);
         \System::log('Image "' . $strFile . '" could not be processed', __METHOD__, TL_ERROR);
         return null;
     }
     imagecopyresampled($strNewImage, $strSourceImage, 0, 0, intval($intPositionX), intval($intPositionY), $this->arrAvatarSize[0], $this->arrAvatarSize[1], $this->arrAvatarSize[0], $this->arrAvatarSize[1]);
     // Create the new image
     switch ($strExtension) {
         case 'gif':
             imagegif($strNewImage, TL_ROOT . '/' . $strThumbnail);
             break;
         case 'jpg':
         case 'jpeg':
             imagejpeg($strNewImage, TL_ROOT . '/' . $strThumbnail, !$GLOBALS['TL_CONFIG']['jpgQuality'] ? 80 : $GLOBALS['TL_CONFIG']['jpgQuality']);
             break;
         case 'png':
             // Optimize non-truecolor images (see #2426)
             if (version_compare($strGdVersion, '2.0', '>=') && function_exists('imagecolormatch') && !imageistruecolor($strSourceImage)) {
                 // TODO: make it work with transparent images, too
                 if (imagecolortransparent($strSourceImage) == -1) {
                     $intColors = imagecolorstotal($strSourceImage);
                     // Convert to a palette image
                     // @see http://www.php.net/manual/de/function.imagetruecolortopalette.php#44803
                     if ($intColors > 0 && $intColors < 256) {
                         $wi = imagesx($strNewImage);
                         $he = imagesy($strNewImage);
                         $ch = imagecreatetruecolor($wi, $he);
                         imagecopymerge($ch, $strNewImage, 0, 0, 0, 0, $wi, $he, 100);
                         imagetruecolortopalette($strNewImage, false, $intColors);
                         imagecolormatch($ch, $strNewImage);
                         imagedestroy($ch);
                     }
                 }
             }
             imagepng($strNewImage, TL_ROOT . '/' . $strThumbnail);
             break;
     }
     // Destroy the temporary images
     imagedestroy($strSourceImage);
     imagedestroy($strNewImage);
     return $strThumbnail;
 }
Exemple #18
0
 public function trueColorToPalette()
 {
     $img = imagecreatetruecolor($this->width, $this->height);
     $bga = imagecolorallocatealpha($img, 0, 0, 0, 127);
     imagecolortransparent($img, $bga);
     imagefill($img, 0, 0, $bga);
     imagecopy($img, $this->image, 0, 0, 0, 0, $this->width, $this->height);
     imagetruecolortopalette($img, false, 255);
     imagesavealpha($img, true);
     if (imageistruecolor($this->image)) {
         $this->log("Matching colors with true color image.");
         imagecolormatch($this->image, $img);
     }
     $this->image = $img;
 }
 private function _getFilePath($file = null)
 {
     // If this is not an image just return path in Database
     if ($file['is_image'] != 1) {
         return $file['server_path'];
     }
     $file_path = $file['server_path'];
     $_get = !empty($_GET) ? $_GET : array();
     $this->_setFileProps($file);
     if (count($_get)) {
         $file_path_params = '';
         $request_w = $this->input->get('w');
         // Width
         $request_h = $this->input->get('h');
         // Height
         $request_m = $this->input->get('m');
         // Mode
         $request_p = $this->input->get('p');
         // Preview (black/white, 8 bit)
         $request_bw = $this->input->get('bw');
         // Grayscale
         $request_c = $this->input->get('c');
         // Crop
         $request_s = $this->input->get('s');
         // Sharpen
         if ($request_w && !empty($this->MODULE_CONF['max_width']) && $request_w > $this->MODULE_CONF['max_width']) {
             show_error('Invalid request. Resize width above allowed size.');
         }
         if ($request_h && !empty($this->MODULE_CONF['max_height']) && $request_h > $this->MODULE_CONF['max_height']) {
             show_error('Invalid request. Resize height above allowed size.');
         }
         if ($request_w) {
             $file_path_params .= '_w' . $request_w;
         }
         if ($request_h) {
             $file_path_params .= '_h' . $request_h;
         }
         if ($request_m) {
             $file_path_params .= '_m' . $request_m;
         }
         if ($request_p) {
             $file_path_params .= '_p' . $request_p;
         }
         if ($request_c) {
             $file_path_params .= '_c' . $request_c;
         }
         if ($request_s) {
             $file_path_params .= '_s' . $request_s;
         }
         if ($request_bw) {
             $file_path_params .= '_bw';
         }
         $new_file_path = $file['base_path'] . $file_path_params . $file['ext'];
         // Does the file exist and make sure the original has not been updated since
         if ($this->show_cached && file_exists($new_file_path) && filemtime($new_file_path) > filemtime($file_path)) {
             // Loading existing file from disk
             return $new_file_path;
         } else {
             // Create a new file
             if (!is_writable(dirname($new_file_path))) {
                 exit('ERROR: Can not write to path: ' . $new_file_path);
             }
             // Create image resource
             switch ($this->image_type) {
                 case 1:
                     $src_img = imagecreatefromgif($file_path);
                     break;
                 case 2:
                     $src_img = imagecreatefromjpeg($file_path);
                     break;
                 case 3:
                     $src_img = imagecreatefrompng($file_path);
                     break;
                 default:
                     show_error('Invalid image type. (' . $file['mime'] . ')');
                     break;
             }
             $crop = false;
             $mode = $this->input->get('m');
             $output_w = $this->input->get('w');
             $output_h = $this->input->get('h');
             $scale_w = $output_w;
             $scale_h = $output_h;
             $file_w = $file['options']['image_width'];
             $file_h = $file['options']['image_height'];
             if ($output_w && $output_h) {
                 if ($mode == 'p') {
                     // p = Fit to size, padded
                     $color = 'ff00ff';
                     $color = $this->_rgb2array($color);
                     $scale = min($output_w / $file_w, $output_h / $file_h);
                     $crop_w = floor($scale * $file_w);
                     $crop_h = floor($scale * $file_h);
                     $crop_x = $file_w - $scale * $output_w;
                     $crop_y = $file_h - $scale * $output_h;
                     $crop = ImageCreateTrueColor($output_w, $output_h);
                     $fill = ImageColorAllocate($crop, $color[0], $color[1], $color[2]);
                     ImageFill($crop, 0, 0, $fill);
                     ImageCopy($crop, $src_img, 0, 0, $crop_x / 2, $crop_y / 2, $crop_w, $crop_h);
                     header('Content-Type: image/jpeg');
                     imagejpeg($crop, NULL, $this->jpg_quality);
                     exit;
                     /*
                     pr($scale, 'scale');
                     pr($crop_x, 'crop_x');
                     pr($crop_y, 'crop_y');
                     pr($crop_w, 'crop_w');
                     pr($crop_h, 'crop_h');
                                     
                     // crop the middle part of the image to fit proportions
                     ImageCopy($crop, $src_img, 0, 0, ($crop_x/2), ($crop_y/2), $crop_w, $crop_h);                       
                     
                     exit();
                     */
                 } else {
                     if ($mode == 'e') {
                         // e = Exact Fit / Crop
                         $scale = min($file_w / $output_w, $file_h / $output_h);
                         $crop_x = $file_w - $scale * $output_w;
                         $crop_y = $file_h - $scale * $output_h;
                         $crop_w = $file_w - $crop_x;
                         $crop_h = $file_h - $crop_y;
                         $crop = ImageCreateTrueColor($crop_w, $crop_h);
                         if ($request_c == 't') {
                             // crop the top center part of the image to fit proportions
                             ImageCopy($crop, $src_img, 0, 0, 0, $crop_y / 2, $crop_w, $crop_h);
                         } else {
                             if ($request_c == 'tl') {
                                 // crop the top left part of the image to fit proportions
                                 ImageCopy($crop, $src_img, 0, 0, 0, 0, $crop_w, $crop_h);
                             } else {
                                 // crop the middle part of the image to fit proportions
                                 ImageCopy($crop, $src_img, 0, 0, $crop_x / 2, $crop_y / 2, $crop_w, $crop_h);
                             }
                         }
                     } else {
                         // w = Fit within
                         $scale = min($output_w / $file_w, $output_h / $file_h);
                         $output_w = floor($scale * $file_w);
                         $output_h = floor($scale * $file_h);
                     }
                 }
             } else {
                 if ($output_h) {
                     $output_w = $output_h * 100 / $file_h * $file_w / 100;
                 } else {
                     if ($output_w) {
                         $output_h = $output_w * 100 / $file_w * $file_h / 100;
                     }
                 }
             }
             // Make scaled image
             $dest_img = ImageCreateTrueColor($output_w, $output_h);
             if ($crop) {
                 // Create new image from cropped source
                 ImageCopyResampled($dest_img, $crop, 0, 0, 0, 0, $output_w, $output_h, $crop_w, $crop_h);
                 ImageDestroy($crop);
             } else {
                 // Create new image from original source
                 ImageCopyResampled($dest_img, $src_img, 0, 0, 0, 0, $output_w, $output_h, $file_w, $file_h);
             }
             // Adjust image quality
             if ($request_bw) {
                 // Greyscale and adjust contrast
                 imagefilter($dest_img, IMG_FILTER_CONTRAST, 5);
                 imagefilter($dest_img, IMG_FILTER_GRAYSCALE);
                 $dest_copy = imagecreatetruecolor($output_w, $output_h);
                 imagecopy($dest_copy, $dest_img, 0, 0, 0, 0, $output_w, $output_h);
                 imagetruecolortopalette($dest_img, $dither, $colors);
                 imagecolormatch($dest_copy, $dest_img);
                 imagedestroy($dest_copy);
             }
             // Adjust image quality
             if ($request_p) {
                 // Force serving as GIF
                 $this->image_type = 1;
                 // Greyscale and adjust contrast
                 imagefilter($dest_img, IMG_FILTER_CONTRAST, -30);
                 imagefilter($dest_img, IMG_FILTER_GRAYSCALE);
                 // Reduce color palette
                 // http://www.php.net/manual/en/function.imagetruecolortopalette.php
                 // zmorris at zsculpt dot com (17-Aug-2004 06:58)
                 $colors = 5;
                 $colors = max(min($colors, 256), 2);
                 $dither = TRUE;
                 $dest_copy = imagecreatetruecolor($output_w, $output_h);
                 imagecopy($dest_copy, $dest_img, 0, 0, 0, 0, $output_w, $output_h);
                 imagetruecolortopalette($dest_img, $dither, $colors);
                 imagecolormatch($dest_copy, $dest_img);
                 imagedestroy($dest_copy);
             }
             // Sharpen Image
             if ($request_s) {
                 $matrix = array(array(-1.2, -1, -1.2), array(-1, $request_s, -1), array(-1.2, -1, -1.2));
                 $divisor = array_sum(array_map('array_sum', $matrix));
                 $offset = 0;
                 imageconvolution($dest_img, $matrix, $divisor, $offset);
             }
             switch ($this->image_type) {
                 case 1:
                     imagegif($dest_img, $new_file_path);
                     break;
                 case 2:
                     imagejpeg($dest_img, $new_file_path, $this->jpg_quality);
                     break;
                 case 3:
                     imagepng($dest_img, $new_file_path);
                     break;
                 default:
                     break;
             }
             ImageDestroy($dest_img);
             ImageDestroy($src_img);
         }
         // Return the newly created file path
         return $new_file_path;
     }
     return $file_path;
 }
function ImageTrueColorToPalette2($image, $dither, $ncolors)
{
    $width = imagesx($image);
    $height = imagesy($image);
    $colors_handle = ImageCreateTrueColor($width, $height);
    @imagecopymerge($colors_handle, $image, 0, 0, 0, 0, $width, $height, 100);
    @imagetruecolortopalette($image, $dither, $ncolors);
    if (function_exists('imagecolormatch')) {
        @imagecolormatch($colors_handle, $image);
    }
    //@imagedestroy($colors_handle);
    return $image;
}
 private function _getFilePath($file = null)
 {
     // If this is not an image just return path in Database
     if ($file['is_image'] != 1) {
         return $file['server_path'];
     }
     $file_path = $file['server_path'];
     $this->_setFileProps($file);
     if ($this->input->get('w') || $this->input->get('h')) {
         $file_path_params = '';
         $request_w = $this->input->get('w');
         $request_h = $this->input->get('h');
         $request_m = $this->input->get('m');
         $request_p = $this->input->get('p');
         if ($request_w && !empty($this->MODULE_CONF['max_width']) && $request_w > $this->MODULE_CONF['max_width']) {
             show_error('Invalid request. Resize width above allowed size.');
         }
         if ($request_h && !empty($this->MODULE_CONF['max_height']) && $request_h > $this->MODULE_CONF['max_height']) {
             show_error('Invalid request. Resize height above allowed size.');
         }
         if ($request_w) {
             $file_path_params .= '_w' . $request_w;
         }
         if ($request_h) {
             $file_path_params .= '_h' . $request_h;
         }
         if ($request_m) {
             $file_path_params .= '_m' . $request_m;
         }
         if ($request_p) {
             $file_path_params .= '_p' . $request_p;
         }
         $quality = 90;
         $new_file_path = $file['base_path'] . $file_path_params . $file['ext'];
         // Does the file exist and make sure the original has not been updated since
         if (file_exists($new_file_path) && filemtime($new_file_path) > filemtime($file_path)) {
             // Loading existing file from disk
             log_message('debug', 'Loading file from disk (' . $new_file_path . ')');
             return $new_file_path;
         } else {
             // Create a new file
             log_message('debug', 'Crating new file (' . $new_file_path . ')');
             if (!is_writable(dirname($new_file_path))) {
                 log_message('debug', 'Can not write to path: ' . $new_file_path);
                 exit('ERROR: Can not write to path: ' . $new_file_path);
             }
             // Create image resource
             switch ($this->image_type) {
                 case 1:
                     $src_img = imagecreatefromgif($file_path);
                     break;
                 case 2:
                     $src_img = imagecreatefromjpeg($file_path);
                     break;
                 case 3:
                     $src_img = imagecreatefrompng($file_path);
                     break;
                 default:
                     show_error('Invalid image type. (' . $file['mime'] . ')');
                     break;
             }
             $props = $this->_getResizeProps($file);
             $dest_img = imagecreatetruecolor($props['w'], $props['h']);
             // Resize image
             if ($this->input->get('w') || $this->input->get('h')) {
                 imagecopyresampled($dest_img, $src_img, 0, 0, $props['x'], $props['y'], $props['w'], $props['h'], $this->image_w, $this->image_h);
             }
             // Adjust image quality
             if ($request_p) {
                 // Force serving as GIF
                 $this->image_type = 1;
                 // Greyscale
                 imagefilter($dest_img, IMG_FILTER_CONTRAST, -30);
                 imagefilter($dest_img, IMG_FILTER_GRAYSCALE);
                 // Reduce color palette
                 // http://www.php.net/manual/en/function.imagetruecolortopalette.php
                 // zmorris at zsculpt dot com (17-Aug-2004 06:58)
                 $colors = 5;
                 $colors = max(min($colors, 256), 2);
                 $dither = TRUE;
                 $dest_copy = imagecreatetruecolor($props['w'], $props['h']);
                 imagecopy($dest_copy, $dest_img, 0, 0, 0, 0, $props['w'], $props['h']);
                 imagetruecolortopalette($dest_img, $dither, $colors);
                 imagecolormatch($dest_copy, $dest_img);
                 imagedestroy($dest_copy);
             }
             switch ($this->image_type) {
                 case 1:
                     imagegif($dest_img, $new_file_path);
                     break;
                 case 2:
                     imagejpeg($dest_img, $new_file_path, $quality);
                     break;
                 case 3:
                     imagepng($dest_img, $new_file_path);
                     break;
                 default:
                     break;
             }
             imagedestroy($dest_img);
             imagedestroy($src_img);
             // TODO: chmod
         }
         // Return the newly created file path
         return $new_file_path;
     }
     return $file_path;
 }