<?php
/**
 *  Уменьшение изображений до заданного размера.
 */

class ImageResampler {
   public function createThumbnail ($image_file, $tn_file, $max_width, $max_height = 0, $what2do = 'TN', $output_format = '') {

       if (!file_exists ($image_file)) return;
       if (!$tn_file) return;

       $image_file_ext = ''; if (strrpos ($image_file, '.')) $image_file_ext = substr ($image_file, strrpos ($image_file, '.'));
       $tn_file_ext = ''; if (strrpos ($tn_file, '.')) $tn_file_ext = substr ($tn_file, strrpos ($tn_file, '.'));

       $img_picture = '';
       if ($image_file_ext == '.jpg') $img_picture = imageCreateFromJPEG ($image_file);
       if ($image_file_ext == '.png') $img_picture = imageCreateFromPNG ($image_file);
       if ($image_file_ext == '.gif') $img_picture = imageCreateFromGIF ($image_file);
       if (!$img_picture) return;

       $size = getImageSize ($image_file);
       if (!is_array ($size)) return;

       $width = $size[0]; if (!$width) return;
       $height = $size[1]; if (!$height) return;

       /* * */

       if (!$max_height) $max_height = $max_width * 1024;

       $required_width = $width;
       $required_height = $height;

       for ($zoom = 0; $zoom <= 1000; $zoom ++) {
            if ($required_width <= $max_width &&
                $required_height <= $max_height) break;

            if ($zoom == 0) {
                $required_width = (int) ($width / 3 * 2);
                $required_height = (int) ($height / 3 * 2);
            } else {
                $required_width = (int) ($width / $zoom);
                $required_height = (int) ($height / $zoom);
            }
       }
       unset ($zoom);

       if ($what2do == 'IMG' && $required_width == $width) return;

       $img_resampled = imageCreateTrueColor ($required_width, $required_height);
       imageCopyResampled ($img_resampled, $img_picture, 0, 0, 0, 0, $required_width, $required_height, $width, $height);

       if (file_exists ($tn_file)) unlink ($tn_file);

       if ($output_format && $output_format == 'PNG') {
           $tn_file = strreplace ($tn_file, $tn_file_ext, '.png');

           imagePNG ($img_resampled, $tn_file);
       } else {
           $quality = 1;
           if ($what2do == 'TN') $quality = 75;
           if ($what2do == 'IMG') $quality = 95;

           $tn_file = strreplace ($tn_file, $tn_file_ext, '.jpg');

           imageJPEG ($img_resampled, $tn_file, $quality);
       }

       /* * */

       imageDestroy ($img_resampled); unset ($img_resampled);
       imageDestroy ($img_picture); unset ($img_picture);
   }
}
?>