Exemple #1
0
 /**
  * write thumbnail file
  * @param	infile	image file name
  * @param	outfile	array of thumb file names (1...n)
  * @return	boolean, true indicates success
  */
 function write($infile, $outfile)
 {
     global $verbose;
     if ($verbose) {
         echo "writing thumb nail...";
     }
     ### Info über Source (SRC) holen
     $temp = getimagesize($infile);
     $this->_SRC['file'] = $infile;
     $this->_SRC['width'] = $temp[0];
     $this->_SRC['height'] = $temp[1];
     $this->_SRC['type'] = $temp[2];
     // 1=GIF, 2=JPG, 3=PNG, SWF=4
     $this->_SRC['string'] = $temp[3];
     $this->_SRC['filename'] = basename($infile);
     //$this->_SRC['modified'] 	= filemtime($infile);
     //Prüfen ob das Orginalbild hoch oder querformatig ist
     if ($this->_SRC['width'] >= $this->_SRC['height']) {
         $this->_SRC['format'] = 'landscape';
     } else {
         $this->_SRC['format'] = 'portrait';
     }
     ### Info über Destination (DST) holen
     if (is_numeric($this->width) and empty($this->height)) {
         $this->_DST['width'] = $this->width;
         $this->_DST['height'] = round($this->width / ($this->_SRC['width'] / $this->_SRC['height']));
     } elseif (is_numeric($this->height) and empty($this->width)) {
         $this->_DST['height'] = $this->height;
         $this->_DST['width'] = round($this->height / ($this->_SRC['height'] / $this->_SRC['width']));
     } elseif (is_numeric($this->width) and is_numeric($this->height)) {
         $this->_DST['width'] = $this->width;
         $this->_DST['height'] = $this->height;
     } elseif (is_numeric($this->longside) and empty($this->shortside)) {
         // Das Größenverhältnis soll erhalten bleiben egal ob das Bild hoch oder querformatig ist.
         // Hier wurde die lange Seite angegeben
         if ($this->_SRC['format'] == 'portrait') {
             $this->_DST['height'] = $this->longside;
             $this->_DST['width'] = round($this->longside / ($this->_SRC['height'] / $this->_SRC['width']));
         } else {
             $this->_DST['width'] = $this->longside;
             $this->_DST['height'] = round($longside / ($this->_SRC['width'] / $this->_SRC['height']));
         }
     } elseif (is_numeric($this->shortside)) {
         // Das Größenverhältnis soll erhalten bleiben egal ob das Bild hoch oder querformatig ist.
         // aber hier wurde die kurze Seite angeben.
         if ($this->_SRC['format'] == 'portrait') {
             $this->_DST['width'] = $this->shortside;
             $this->_DST['height'] = round($this->shortside / ($this->_SRC['width'] / $this->_SRC['height']));
         } else {
             $this->_DST['height'] = $this->shortside;
             $this->_DST['width'] = round($this->shortside / ($this->_SRC['height'] / $this->_SRC['width']));
         }
     } else {
         // default dimensions
         $this->width = 100;
         $this->_DST['width'] = $this->width;
         $this->_DST['height'] = round($this->width / ($this->_SRC['width'] / $this->_SRC['height']));
     }
     // Wenn das Ursprungsbild kleiner als das Ziel-Bild ist, soll nicht hochskaliert werden
     if ($this->extrapolate === false && $this->_DST['height'] > $this->_SRC['height'] && $this->_DST['width'] > $this->_SRC['width']) {
         $this->_DST['width'] = $this->_SRC['width'];
         $this->_DST['height'] = $this->_SRC['height'];
     }
     $this->_DST['type'] = $this->_SRC['type'];
     $this->_DST['file'] = $outfile;
     // SRC einlesen
     if ($this->_SRC['type'] == 1) {
         $this->_SRC['image'] = imagecreatefromgif($this->_SRC['file']);
     } elseif ($this->_SRC['type'] == 2) {
         $this->_SRC['image'] = imagecreatefromjpeg($this->_SRC['file']);
     } elseif ($this->_SRC['type'] == 3) {
         $this->_SRC['image'] = imagecreatefrompng($this->_SRC['file']);
     }
     // Soll beschnitten werden?
     $off_w = 0;
     $off_h = 0;
     if ($this->crop != false) {
         if ($this->_SRC['height'] < $this->_SRC['width']) {
             $ratio = (double) ($this->_SRC['height'] / $this->_DST['height']);
             $cpyWidth = round($this->_DST['width'] * $ratio);
             if ($cpyWidth > $this->_SRC['width']) {
                 $ratio = (double) ($this->_SRC['width'] / $this->_DST['width']);
                 $cpyWidth = $this->_SRC['width'];
                 $cpyHeight = round($this->_DST['height'] * $ratio);
                 $off_w = 0;
                 $off_h = round(($this->_SRC['height'] - $cpyHeight) / 2);
                 $this->_SRC['height'] = $cpyHeight;
             } else {
                 $cpyHeight = $this->_SRC['height'];
                 $off_w = round(($this->_SRC['width'] - $cpyWidth) / 2);
                 $off_h = 0;
                 $this->_SRC['width'] = $cpyWidth;
             }
         } else {
             $ratio = (double) ($this->_SRC['width'] / $this->_DST['width']);
             $cpyHeight = round($this->_DST['height'] * $ratio);
             if ($cpyHeight > $this->_SRC['height']) {
                 $ratio = (double) ($this->_SRC['height'] / $this->_DST['height']);
                 $cpyHeight = $this->_SRC['height'];
                 $cpyWidth = round($this->_DST['width'] * $ratio);
                 $off_w = round(($this->_SRC['width'] - $cpyWidth) / 2);
                 $off_h = 0;
                 $this->_SRC['width'] = $cpyWidth;
             } else {
                 $cpyWidth = $this->_SRC['width'];
                 $off_w = 0;
                 $off_h = round(($this->_SRC['height'] - $cpyHeight) / 2);
                 $this->_SRC['height'] = $cpyHeight;
             }
         }
     }
     // DST erstellen
     $this->_DST['image'] = imagecreatetruecolor($this->_DST['width'], $this->_DST['height']);
     imagecopyresampled($this->_DST['image'], $this->_SRC['image'], 0, 0, $off_w, $off_h, $this->_DST['width'], $this->_DST['height'], $this->_SRC['width'], $this->_SRC['height']);
     if ($this->sharpen === true) {
         $this->_DST['image'] = UnsharpMask($this->_DST['image'], 80, 0.5, 3);
     }
     // finally: the real dimensions
     $this->height = $this->_DST['height'];
     $this->width = $this->_DST['width'];
     // Soll eine Lupe eingefügt werden?
     if ($this->hint === true) {
         //Soll der weiße Balken wirklich hinzugefügt werden?
         if ($this->addgreytohint === true) {
             $trans = imagecolorallocatealpha($this->_DST['image'], 255, 255, 255, 25);
             imagefilledrectangle($this->_DST['image'], 0, $this->_DST['height'] - 9, $this->_DST['width'], $this->_DST['height'], $trans);
         }
         $magnifier = imagecreatefromstring(gzuncompress(base64_decode("eJzrDPBz5+WS4mJgYOD19HAJAtLcIMzBBiRXrilXA1IsxU6eIRxAUMOR0gHkcxZ4RBYD1QiBMOOlu3V/gIISJa4RJc5FqYklmfl5CiGZuakMBoZ6hkZ6RgYGJs77ex2BalRBaoLz00rKE4tSGXwTk4vyc1NTMhMV3DKLUsvzi7KLFXwjFEAa2svWnGdgYPTydHEMqZhTOsE++1CAyNHzm2NZjgau+dAmXlAwoatQmOld3t/NPxlLMvY7sovPzXHf7re05BPzjpQTMkZTPjm1HlHkv6clYWK43Zt16rcDjdZ/3j2cd7qD4/HHH3GaprFrw0QZDHicORXl2JsPsveVTDz//L3N+WpxJ5Hff+10Tjdd2/Vi17vea79Om5w9zzyne9GLnWGrN8atby/ayXPOsu2w4quvVtxNCVVz5nAf3nDpZckBCedpqSc28WTOWnT7rZNXZSlPvFybie9EFc6y3bIMCn3JAoJ+kyyfn9qWq+LZ9Las26Jv482cDRE6Ci0B6gVbo2oj9KabzD8vyMK4ZMqMs2kSvW4chz88SXNzmeGjtj1QZK9M3HHL8L7HITX3t19//VVY8CYDg9Kvy2vDXu+6mGGxNOiltMPsjn/t9eJr0ja/FOdi5TyQ9Lz3fOqstOr99/dnro2vZ1jy76D/vYivPsBoYPB09XNZ55TQBAAJjs5s</body>")));
         imagealphablending($this->_DST['image'], true);
         imagecopy($this->_DST['image'], $magnifier, $this->_DST['width'] - 15, $this->_DST['height'] - 14, 0, 0, 11, 11);
         imagedestroy($magnifier);
     }
     if ($verbose) {
         echo "... saving image ...";
     }
     if ($this->_DST['type'] == 1) {
         imagetruecolortopalette($this->_DST['image'], false, 256);
         imagegif($this->_DST['image'], $this->_DST['file']);
     } elseif ($this->_DST['type'] == 2) {
         imagejpeg($this->_DST['image'], $this->_DST['file'], $this->quality);
     } elseif ($this->_DST['type'] == 3) {
         imagepng($this->_DST['image'], $this->_DST['file']);
     }
     if ($verbose) {
         echo "... image successfully saved ...";
     }
     imagedestroy($this->_DST['image']);
     imagedestroy($this->_SRC['image']);
     return true;
 }
Exemple #2
0
 /**
  * Resize
  *
  * @param integer $width  Width
  * @param integer $height Height
  *
  * @return boolean
  */
 public function resize($width, $height)
 {
     $result = false;
     if ($this->image) {
         $newImage = imagecreatetruecolor($width, $height);
         $transparentIndex = imagecolortransparent($this->image);
         if ($transparentIndex >= 0) {
             imagepalettecopy($this->image, $newImage);
             imagefill($newImage, 0, 0, $transparentIndex);
             imagecolortransparent($newImage, $transparentIndex);
             imagetruecolortopalette($newImage, true, 256);
         } else {
             imagealphablending($newImage, false);
             imagesavealpha($newImage, true);
             $transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
             imagefilledrectangle($newImage, 0, 0, $width, $height, $transparent);
         }
         $result = imagecopyresampled($newImage, $this->image, 0, 0, 0, 0, $width, $height, $this->width, $this->height);
         if ($result) {
             imagedestroy($this->image);
             $this->image = $newImage;
             $this->width = $width;
             $this->height = $height;
             if (\XLite::getInstance()->getOptions(array('images', 'unsharp_mask_filter_on_resize'))) {
                 include_once LC_DIR_LIB . 'phpunsharpmask.php';
                 $unsharpImage = UnsharpMask($this->image);
                 if ($unsharpImage) {
                     $this->image = $unsharpImage;
                 }
             }
         }
     }
     return $result;
 }
function thumbnail($filename, $source_path, $target_path, $thumb_width, $thumb_height, $is_create, $is_crop = false, $crop_mode = 'center', $is_sharpen = false, $um_value = '80/0.5/3')
{
    global $g5;
    if (!$thumb_width && !$thumb_height) {
        return;
    }
    $source_file = "{$source_path}/{$filename}";
    if (!is_file($source_file)) {
        // 원본 파일이 없다면
        return;
    }
    $size = @getimagesize($source_file);
    if ($size[2] < 1 || $size[2] > 3) {
        // gif, jpg, png 에 대해서만 적용
        return;
    }
    if (!is_dir($target_path)) {
        @mkdir($target_path, G5_DIR_PERMISSION);
        @chmod($target_path, G5_DIR_PERMISSION);
    }
    // 디렉토리가 존재하지 않거나 쓰기 권한이 없으면 썸네일 생성하지 않음
    if (!(is_dir($target_path) && is_writable($target_path))) {
        return '';
    }
    // Animated GIF는 썸네일 생성하지 않음
    if ($size[2] == 1) {
        if (is_animated_gif($source_file)) {
            return basename($source_file);
        }
    }
    $ext = array(1 => 'gif', 2 => 'jpg', 3 => 'png');
    $thumb_filename = preg_replace("/\\.[^\\.]+\$/i", "", $filename);
    // 확장자제거
    $thumb_file = "{$target_path}/thumb-{$thumb_filename}_{$thumb_width}x{$thumb_height}." . $ext[$size[2]];
    $thumb_time = @filemtime($thumb_file);
    $source_time = @filemtime($source_file);
    if (file_exists($thumb_file)) {
        if ($is_create == false && $source_time < $thumb_time) {
            return basename($thumb_file);
        }
    }
    // 원본파일의 GD 이미지 생성
    $src = null;
    $degree = 0;
    if ($size[2] == 1) {
        $src = imagecreatefromgif($source_file);
        $src_transparency = imagecolortransparent($src);
    } else {
        if ($size[2] == 2) {
            $src = imagecreatefromjpeg($source_file);
            if (function_exists('exif_read_data')) {
                // exif 정보를 기준으로 회전각도 구함
                $exif = @exif_read_data($source_file);
                if (!empty($exif['Orientation'])) {
                    switch ($exif['Orientation']) {
                        case 8:
                            $degree = 90;
                            break;
                        case 3:
                            $degree = 180;
                            break;
                        case 6:
                            $degree = -90;
                            break;
                    }
                    // 회전각도 있으면 이미지 회전
                    if ($degree) {
                        $src = imagerotate($src, $degree, 0);
                        // 세로사진의 경우 가로, 세로 값 바꿈
                        if ($degree == 90 || $degree == -90) {
                            $tmp = $size;
                            $size[0] = $tmp[1];
                            $size[1] = $tmp[0];
                        }
                    }
                }
            }
        } else {
            if ($size[2] == 3) {
                $src = imagecreatefrompng($source_file);
                imagealphablending($src, true);
            } else {
                return;
            }
        }
    }
    if (!$src) {
        return;
    }
    $is_large = true;
    // width, height 설정
    if ($thumb_width) {
        if (!$thumb_height) {
            $thumb_height = round($thumb_width * $size[1] / $size[0]);
        } else {
            if ($size[0] < $thumb_width || $size[1] < $thumb_height) {
                $is_large = false;
            }
        }
    } else {
        if ($thumb_height) {
            $thumb_width = round($thumb_height * $size[0] / $size[1]);
        }
    }
    $dst_x = 0;
    $dst_y = 0;
    $src_x = 0;
    $src_y = 0;
    $dst_w = $thumb_width;
    $dst_h = $thumb_height;
    $src_w = $size[0];
    $src_h = $size[1];
    $ratio = $dst_h / $dst_w;
    if ($is_large) {
        // 크롭처리
        if ($is_crop) {
            switch ($crop_mode) {
                case 'center':
                    if ($size[1] / $size[0] >= $ratio) {
                        $src_h = round($src_w * $ratio);
                        $src_y = round(($size[1] - $src_h) / 2);
                    } else {
                        $src_w = round($size[1] / $ratio);
                        $src_x = round(($size[0] - $src_w) / 2);
                    }
                    break;
                default:
                    if ($size[1] / $size[0] >= $ratio) {
                        $src_h = round($src_w * $ratio);
                    } else {
                        $src_w = round($size[1] / $ratio);
                    }
                    break;
            }
        }
        $dst = imagecreatetruecolor($dst_w, $dst_h);
        if ($size[2] == 3) {
            imagealphablending($dst, false);
            imagesavealpha($dst, true);
        } else {
            if ($size[2] == 1) {
                $palletsize = imagecolorstotal($src);
                if ($src_transparency >= 0 && $src_transparency < $palletsize) {
                    $transparent_color = imagecolorsforindex($src, $src_transparency);
                    $current_transparent = imagecolorallocate($dst, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
                    imagefill($dst, 0, 0, $current_transparent);
                    imagecolortransparent($dst, $current_transparent);
                }
            }
        }
    } else {
        $dst = imagecreatetruecolor($dst_w, $dst_h);
        $bgcolor = imagecolorallocate($dst, 255, 255, 255);
        // 배경색
        if ($src_w < $dst_w) {
            if ($src_h >= $dst_h) {
                $dst_x = round(($dst_w - $src_w) / 2);
                $src_h = $dst_h;
            } else {
                $dst_x = round(($dst_w - $src_w) / 2);
                $dst_y = round(($dst_h - $src_h) / 2);
                $dst_w = $src_w;
                $dst_h = $src_h;
            }
        } else {
            if ($src_h < $dst_h) {
                $dst_y = round(($dst_h - $src_h) / 2);
                $dst_h = $src_h;
                $src_w = $dst_w;
            }
        }
        if ($size[2] == 3) {
            $bgcolor = imagecolorallocatealpha($dst, 0, 0, 0, 127);
            imagefill($dst, 0, 0, $bgcolor);
            imagealphablending($dst, false);
            imagesavealpha($dst, true);
        } else {
            if ($size[2] == 1) {
                $palletsize = imagecolorstotal($src);
                if ($src_transparency >= 0 && $src_transparency < $palletsize) {
                    $transparent_color = imagecolorsforindex($src, $src_transparency);
                    $current_transparent = imagecolorallocate($dst, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
                    imagefill($dst, 0, 0, $current_transparent);
                    imagecolortransparent($dst, $current_transparent);
                } else {
                    imagefill($dst, 0, 0, $bgcolor);
                }
            } else {
                imagefill($dst, 0, 0, $bgcolor);
            }
        }
    }
    imagecopyresampled($dst, $src, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
    // sharpen 적용
    if ($is_sharpen && $is_large) {
        $val = explode('/', $um_value);
        UnsharpMask($dst, $val[0], $val[1], $val[2]);
    }
    if ($size[2] == 1) {
        imagegif($dst, $thumb_file);
    } else {
        if ($size[2] == 3) {
            if (!defined('G5_THUMB_PNG_COMPRESS')) {
                $png_compress = 5;
            } else {
                $png_compress = G5_THUMB_PNG_COMPRESS;
            }
            imagepng($dst, $thumb_file, $png_compress);
        } else {
            if (!defined('G5_THUMB_JPG_QUALITY')) {
                $jpg_quality = 90;
            } else {
                $jpg_quality = G5_THUMB_JPG_QUALITY;
            }
            imagejpeg($dst, $thumb_file, $jpg_quality);
        }
    }
    chmod($thumb_file, G5_FILE_PERMISSION);
    // 추후 삭제를 위하여 파일모드 변경
    imagedestroy($src);
    imagedestroy($dst);
    return basename($thumb_file);
}
Exemple #4
0
        }
    }
}
$im = @ImageCreateFromJPEG($img) or $im = @ImageCreateFromPNG($img) or $im = @ImageCreateFromGIF($img) or $im = false;
// If image is not JPEG, PNG, or GIF
if (!$im) {
    // We get errors from PHP's ImageCreate functions...
    // So let's echo back the contents of the actual image.
    readfile($img);
} else {
    // Create the resized image destination
    $thumb = @ImageCreateTrueColor($w, $h);
    // Copy from image source, resize it, and paste to image destination
    @ImageCopyResampled($thumb, $im, 0, 0, 0, 0, $w, $h, $sw, $sh);
    if ($unsharp == 1) {
        $thumb = UnsharpMask($thumb, 100, 0.8, 2);
    }
    // Output resized image
    @ImageJPEG($thumb);
}
/*
New: 
- In version 2.1 (February 26 2007) Tom Bishop has done some important speed enhancements.
- From version 2 (July 17 2006) the script uses the imageconvolution function in PHP 
version >= 5.1, which improves the performance considerably.
Unsharp masking is a traditional darkroom technique that has proven very suitable for 
digital imaging. The principle of unsharp masking is to create a blurred copy of the image
and compare it to the underlying original. The difference in colour values
between the two images is greatest for the pixels near sharp edges. When this 
difference is subtracted from the original image, the edges will be
accentuated. 
Exemple #5
0
function MakeThumbnail($upfiledir, $src, $tName, $tw = '', $th = '', $scale = true, $tDir = "thumb")
{
    global $iCMS;
    $R = array();
    $image = "";
    $tMap = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
    $tw = empty($tw) ? (int) $iCMS->config['thumbwidth'] : $tw;
    $th = empty($th) ? (int) $iCMS->config['thumbhight'] : $th;
    if ($tw && $th) {
        list($width, $height, $type) = @getimagesize($src);
        if ($width < 1 && $height < 1) {
            $R['width'] = $tw;
            $R['height'] = $th;
            $R['src'] = $src;
            return $R;
        }
        if ($width > $tw || $height > $th) {
            createdir($upfiledir . $tDir);
            if ($scale) {
                $im = scale_image(array("mw" => $tw, "mh" => $th, "cw" => $width, "ch" => $height));
            } else {
                $im = array('w' => $tw, 'h' => $th);
            }
            $R['width'] = $im['w'];
            $R['height'] = $im['h'];
            $tName .= '_' . $R['width'] . 'x' . $R['height'];
            $img = icf($tMap[$type], $src);
            if ($img['res']) {
                $thumb = imagecreatetruecolor($im['w'], $im['h']);
                imagecopyresampled($thumb, $img['res'], 0, 0, 0, 0, $im['w'], $im['h'], $width, $height);
                PHP_VERSION != '4.3.2' && UnsharpMask($thumb);
                $R['src'] = $upfiledir . $tDir . "/" . $tName;
                __image($thumb, $img['type'], $R['src']);
                $R['src'] .= '.' . $img['type'];
            } else {
                $R['src'] = $src;
            }
        } else {
            $R['width'] = $width;
            $R['height'] = $height;
            $R['src'] = $src;
        }
        return $R;
    }
}
            $pseudo_pic_height = $pic_height;
            $a = 0;
            $b = 0;
            $x = 0;
            $y = 0;
        }
    }
}
$thumbnail = $album_config['gd_version'] == 1 ? @imagecreate($thumbnail_width, $thumbnail_height) : @imagecreatetruecolor($thumbnail_width, $thumbnail_height);
$resize_function = $album_config['gd_version'] == 1 ? 'imagecopyresized' : 'imagecopyresampled';
@$resize_function($thumbnail, $src, $a, $b, $x, $y, $thumbnail_width, $thumbnail_height, $pseudo_pic_width, $pseudo_pic_height);
if ($sharpen == 1) {
    $amount = $album_config['sharpen_amount'];
    $radius = $album_config['sharpen_radius'];
    $threshold = $album_config['sharpen_threshold'];
    $thumbnail = UnsharpMask($thumbnail, $amount, $radius, $threshold);
}
if ($raster == 1) {
    if ($album_config['raster_line_color'] == "") {
        $album_config['raster_line_color'] == "000000";
    }
    $col = $album_config['raster_line_color'];
    $col = ImageColorAllocateHEX($thumbnail, $col);
    for ($i = 0; $i < $thumbnail_height + 1; $i++) {
        ImageLine($thumbnail, 1, $i, $thumbnail_width - 1, $i, $col);
        $i++;
    }
}
if ($colorize == 1) {
    $border_value = 0;
    $border2_value = 0;
function generate_thumbnail($attach_thumb = array())
{
    global $options, $attachsubdir;
    $return = array();
    $image = '';
    $thumb_file = $attach_thumb['filepath'];
    $remap = array(1 => 'gif', 2 => 'jpg', 3 => 'png');
    if ($attach_thumb['thumbswidth'] && $attach_thumb['thumbsheight']) {
        $filesize = @GetImageSize($thumb_file);
        if ($filesize[0] < 1 && $filesize[1] < 1) {
            $filesize = array();
            $filesize[0] = $attach_thumb['thumbswidth'];
            $filesize[1] = $attach_thumb['thumbsheight'];
            $return['thumbwidth'] = $attach_thumb['thumbswidth'];
            $return['thumbheight'] = $attach_thumb['thumbsheight'];
            $return['thumbfilepath'] = $attach_thumb['filepath'];
            return $return;
        }
        if ($filesize[0] > $thumb['thumbswidth'] || $filesize[1] > $attach_thumb['thumbsheight']) {
            $im = scale_image(array('max_width' => $attach_thumb['thumbswidth'], 'max_height' => $attach_thumb['thumbsheight'], 'cur_width' => $filesize[0], 'cur_height' => $filesize[1]));
            $return['thumbwidth'] = $im['img_width'];
            $return['thumbheight'] = $im['img_height'];
            if ($remap[$filesize[2]] == 'gif') {
                if (function_exists('imagecreatefromgif')) {
                    if (!($image = @imagecreatefromgif($thumb_file))) {
                        redirect($attach_thumb['filename'] . '文件生成缩略图失败');
                    }
                    $type = 'gif';
                }
            } else {
                if ($remap[$filesize[2]] == 'png') {
                    if (function_exists('imagecreatefrompng')) {
                        if (!($image = @imagecreatefrompng($thumb_file))) {
                            redirect($attach_thumb['filename'] . '文件生成缩略图失败');
                        }
                        $type = 'png';
                    }
                } else {
                    if ($remap[$filesize[2]] == 'jpg') {
                        if (function_exists('imagecreatefromjpeg')) {
                            if (!($image = @imagecreatefromjpeg($thumb_file))) {
                                redirect($attach_thumb['filename'] . '文件生成缩略图失败');
                            }
                            $type = 'jpg';
                        }
                    }
                }
            }
            if ($image) {
                if (function_exists('imagecreatetruecolor')) {
                    $thumb = @imagecreatetruecolor($im['img_width'], $im['img_height']);
                    @imagecopyresampled($thumb, $image, 0, 0, 0, 0, $im['img_width'], $im['img_height'], $filesize[0], $filesize[1]);
                } else {
                    $thumb = @imagecreate($im['img_width'], $im['img_height']);
                    @imagecopyresized($thumb, $image, 0, 0, 0, 0, $im['img_width'], $im['img_height'], $filesize[0], $filesize[1]);
                }
                if (PHP_VERSION != '4.3.2') {
                    UnsharpMask($thumb);
                }
                if (!$thumb_filename) {
                    $thumb_filename = 'thumb_' . $attach_thumb['filename'];
                }
                $file_extension = $attach_thumb['extension'];
                if ($file_extension == 'jpg' && function_exists('imagejpeg')) {
                    @imagejpeg($thumb, SABLOG_ROOT . $options['attachments_dir'] . $attach_thumb['attachsubdir'] . $thumb_filename . '.jpg', 80);
                    @imagedestroy($thumb);
                } else {
                    if ($file_extension == 'png' && function_exists('imagepng')) {
                        @imagepng($thumb, SABLOG_ROOT . $options['attachments_dir'] . $attach_thumb['attachsubdir'] . $thumb_filename . '.png');
                        @imagedestroy($thumb);
                    } else {
                        if ($file_extension == 'gif' && function_exists('imagegif')) {
                            @imagegif($thumb, SABLOG_ROOT . $options['attachments_dir'] . $attach_thumb['attachsubdir'] . $thumb_filename . '.gif');
                            @imagedestroy($thumb);
                        } else {
                            $return['thumbfilepath'] = $thumb['filepath'];
                            return $return;
                        }
                    }
                }
                $return['thumbfilepath'] = $thumb_filename . '.' . $file_extension;
                return $return;
            } else {
                $return['thumbwidth'] = $im['img_width'];
                $return['thumbheight'] = $im['img_height'];
                $return['thumbfilepath'] = $attach_thumb['filepath'];
                return $return;
            }
        } else {
            $return['thumbwidth'] = $filesize[0];
            $return['thumbheight'] = $filesize[1];
            $return['thumbfilepath'] = $attach_thumb['filepath'];
            return $return;
        }
    }
}
/**
 * Check if any effect needs to be applied to the thumbnail
 */
/** Add Unsharp */
if ($_GET['sh']) {
    if ($_GET['sh'] == 1) {
        $cant = 70;
        $radio = 0.5;
        $thres = 3;
    } else {
        $arraysh = explode("|", $_GET['sh']);
        $cant = $arraysh[0];
        $radio = $arraysh[1];
        $thres = $arraysh[2];
    }
    UnsharpMask($output, $cant, $radio, $thres);
}
/** Rotate */
if ($_GET['r']) {
    $arrayr = explode("|", $_GET['r']);
    $grados = $arrayr[0];
    $back = '0x' . $arrayr[1];
    $rotate = imagerotate($output, $grados, $back);
    imagejpeg($rotate, NULL, $thumbnail_quality);
}
/** Add Blur */
if ($_GET['bl']) {
    $blcant = $_GET['bl'];
    blur($output, $blcant);
}
/** Add Pixelate */
Exemple #9
0
function makeThumbnailFullUnsharpMask($vb798abe6e1b1318ee36b0dcb3fb9e4d3, $ve9f40e1f1d1658681dad2dac4ae0971e, $vfc021d54683383e5078ab9fefc4d53c8, $vf0598264a691a8f62272aca0e79af374)
{
    if (function_exists('UnsharpMask')) {
        return UnsharpMask($vb798abe6e1b1318ee36b0dcb3fb9e4d3, $ve9f40e1f1d1658681dad2dac4ae0971e, $vfc021d54683383e5078ab9fefc4d53c8, $vf0598264a691a8f62272aca0e79af374);
    } else {
        if ($ve9f40e1f1d1658681dad2dac4ae0971e > 500) {
            $ve9f40e1f1d1658681dad2dac4ae0971e = 500;
        }
        $ve9f40e1f1d1658681dad2dac4ae0971e = $ve9f40e1f1d1658681dad2dac4ae0971e * 0.016;
        if ($vfc021d54683383e5078ab9fefc4d53c8 > 50) {
            $vfc021d54683383e5078ab9fefc4d53c8 = 50;
        }
        $vfc021d54683383e5078ab9fefc4d53c8 = $vfc021d54683383e5078ab9fefc4d53c8 * 2;
        if ($vf0598264a691a8f62272aca0e79af374 > 255) {
            $vf0598264a691a8f62272aca0e79af374 = 255;
        }
        $vfc021d54683383e5078ab9fefc4d53c8 = abs(round($vfc021d54683383e5078ab9fefc4d53c8));
        if ($vfc021d54683383e5078ab9fefc4d53c8 == 0) {
            return $vb798abe6e1b1318ee36b0dcb3fb9e4d3;
            imagedestroy($vb798abe6e1b1318ee36b0dcb3fb9e4d3);
            break;
        }
        $vf1290186a5d0b1ceab27f4e77c0c5d68 = imagesx($vb798abe6e1b1318ee36b0dcb3fb9e4d3);
        $v2510c39011c5be704182423e3a695e91 = imagesy($vb798abe6e1b1318ee36b0dcb3fb9e4d3);
        $vdd2b9c2d0f89eb88267d945e852649e1 = $vb798abe6e1b1318ee36b0dcb3fb9e4d3;
        $v731eea25c6c42b949dd8b33e55cb622e = $vb798abe6e1b1318ee36b0dcb3fb9e4d3;
        $v0912bfe735bcb6f63b4dc49ae3833df8 = imagecreatetruecolor($vf1290186a5d0b1ceab27f4e77c0c5d68, $v2510c39011c5be704182423e3a695e91);
        for ($v865c0c0b4ab0e063e5caa3387c1a8741 = 0; $v865c0c0b4ab0e063e5caa3387c1a8741 < $vfc021d54683383e5078ab9fefc4d53c8; $v865c0c0b4ab0e063e5caa3387c1a8741++) {
            imagecopy($v0912bfe735bcb6f63b4dc49ae3833df8, $vdd2b9c2d0f89eb88267d945e852649e1, 0, 0, 1, 1, $vf1290186a5d0b1ceab27f4e77c0c5d68 - 1, $v2510c39011c5be704182423e3a695e91 - 1);
            imagecopymerge($v0912bfe735bcb6f63b4dc49ae3833df8, $vdd2b9c2d0f89eb88267d945e852649e1, 1, 1, 0, 0, $vf1290186a5d0b1ceab27f4e77c0c5d68, $v2510c39011c5be704182423e3a695e91, 50);
            imagecopymerge($v0912bfe735bcb6f63b4dc49ae3833df8, $vdd2b9c2d0f89eb88267d945e852649e1, 0, 1, 1, 0, $vf1290186a5d0b1ceab27f4e77c0c5d68 - 1, $v2510c39011c5be704182423e3a695e91, 33.33333);
            imagecopymerge($v0912bfe735bcb6f63b4dc49ae3833df8, $vdd2b9c2d0f89eb88267d945e852649e1, 1, 0, 0, 1, $vf1290186a5d0b1ceab27f4e77c0c5d68, $v2510c39011c5be704182423e3a695e91 - 1, 25);
            imagecopymerge($v0912bfe735bcb6f63b4dc49ae3833df8, $vdd2b9c2d0f89eb88267d945e852649e1, 0, 0, 1, 0, $vf1290186a5d0b1ceab27f4e77c0c5d68 - 1, $v2510c39011c5be704182423e3a695e91, 33.33333);
            imagecopymerge($v0912bfe735bcb6f63b4dc49ae3833df8, $vdd2b9c2d0f89eb88267d945e852649e1, 1, 0, 0, 0, $vf1290186a5d0b1ceab27f4e77c0c5d68, $v2510c39011c5be704182423e3a695e91, 25);
            imagecopymerge($v0912bfe735bcb6f63b4dc49ae3833df8, $vdd2b9c2d0f89eb88267d945e852649e1, 0, 0, 0, 1, $vf1290186a5d0b1ceab27f4e77c0c5d68, $v2510c39011c5be704182423e3a695e91 - 1, 20);
            imagecopymerge($v0912bfe735bcb6f63b4dc49ae3833df8, $vdd2b9c2d0f89eb88267d945e852649e1, 0, 1, 0, 0, $vf1290186a5d0b1ceab27f4e77c0c5d68, $v2510c39011c5be704182423e3a695e91, 16.666667);
            imagecopymerge($v0912bfe735bcb6f63b4dc49ae3833df8, $vdd2b9c2d0f89eb88267d945e852649e1, 0, 0, 0, 0, $vf1290186a5d0b1ceab27f4e77c0c5d68, $v2510c39011c5be704182423e3a695e91, 50);
        }
        $vdd2b9c2d0f89eb88267d945e852649e1 = $v0912bfe735bcb6f63b4dc49ae3833df8;
        for ($v9dd4e461268c8034f5c8564e155c67a6 = 0; $v9dd4e461268c8034f5c8564e155c67a6 < $vf1290186a5d0b1ceab27f4e77c0c5d68; $v9dd4e461268c8034f5c8564e155c67a6++) {
            for ($v415290769594460e2e485922904f345d = 0; $v415290769594460e2e485922904f345d < $v2510c39011c5be704182423e3a695e91; $v415290769594460e2e485922904f345d++) {
                $ve7ee80f9d3ee77a07b7e0e40911d4b85 = ImageColorAt($v731eea25c6c42b949dd8b33e55cb622e, $v9dd4e461268c8034f5c8564e155c67a6, $v415290769594460e2e485922904f345d);
                $vcd8a4c8c79b1ff2c064026bb7cefe760 = $ve7ee80f9d3ee77a07b7e0e40911d4b85 >> 16 & 0xff;
                $vd7fd33dc47e7db31c2bdd232804331bf = $ve7ee80f9d3ee77a07b7e0e40911d4b85 >> 8 & 0xff;
                $v62f533cdf0bda50d31d41662bbe16e8e = $ve7ee80f9d3ee77a07b7e0e40911d4b85 & 0xff;
                $v82d175da0ae7901210ea5d63914f5212 = ImageColorAt($vdd2b9c2d0f89eb88267d945e852649e1, $v9dd4e461268c8034f5c8564e155c67a6, $v415290769594460e2e485922904f345d);
                $v56dc21b41aac91a611402ee281442e54 = $v82d175da0ae7901210ea5d63914f5212 >> 16 & 0xff;
                $vab27a9c8dd988ea5d32cd8f3e763b1b1 = $v82d175da0ae7901210ea5d63914f5212 >> 8 & 0xff;
                $vfbdaa5229703cc85625873f73f1ef573 = $v82d175da0ae7901210ea5d63914f5212 & 0xff;
                $v6c99f2ac4dbbc9ac99a83340dacd50cb = abs($vcd8a4c8c79b1ff2c064026bb7cefe760 - $v56dc21b41aac91a611402ee281442e54) >= $vf0598264a691a8f62272aca0e79af374 ? max(0, min(255, $ve9f40e1f1d1658681dad2dac4ae0971e * ($vcd8a4c8c79b1ff2c064026bb7cefe760 - $v56dc21b41aac91a611402ee281442e54) + $vcd8a4c8c79b1ff2c064026bb7cefe760)) : $vcd8a4c8c79b1ff2c064026bb7cefe760;
                $v8f3e420d187de004189e440099d8e9b8 = abs($vd7fd33dc47e7db31c2bdd232804331bf - $vab27a9c8dd988ea5d32cd8f3e763b1b1) >= $vf0598264a691a8f62272aca0e79af374 ? max(0, min(255, $ve9f40e1f1d1658681dad2dac4ae0971e * ($vd7fd33dc47e7db31c2bdd232804331bf - $vab27a9c8dd988ea5d32cd8f3e763b1b1) + $vd7fd33dc47e7db31c2bdd232804331bf)) : $vd7fd33dc47e7db31c2bdd232804331bf;
                $v4798968467b4ab45ea7902a5084666b8 = abs($v62f533cdf0bda50d31d41662bbe16e8e - $vfbdaa5229703cc85625873f73f1ef573) >= $vf0598264a691a8f62272aca0e79af374 ? max(0, min(255, $ve9f40e1f1d1658681dad2dac4ae0971e * ($v62f533cdf0bda50d31d41662bbe16e8e - $vfbdaa5229703cc85625873f73f1ef573) + $v62f533cdf0bda50d31d41662bbe16e8e)) : $v62f533cdf0bda50d31d41662bbe16e8e;
                if ($vcd8a4c8c79b1ff2c064026bb7cefe760 != $v6c99f2ac4dbbc9ac99a83340dacd50cb || $vd7fd33dc47e7db31c2bdd232804331bf != $v8f3e420d187de004189e440099d8e9b8 || $v62f533cdf0bda50d31d41662bbe16e8e != $v4798968467b4ab45ea7902a5084666b8) {
                    $vfbfe459f582d8ac5384527d6aaadb670 = ImageColorAllocate($vb798abe6e1b1318ee36b0dcb3fb9e4d3, $v6c99f2ac4dbbc9ac99a83340dacd50cb, $v8f3e420d187de004189e440099d8e9b8, $v4798968467b4ab45ea7902a5084666b8);
                    ImageSetPixel($vb798abe6e1b1318ee36b0dcb3fb9e4d3, $v9dd4e461268c8034f5c8564e155c67a6, $v415290769594460e2e485922904f345d, $vfbfe459f582d8ac5384527d6aaadb670);
                }
            }
        }
        return $vb798abe6e1b1318ee36b0dcb3fb9e4d3;
    }
}
         case "gif":
             $fullImage = imagecreatefromgif($_FILES['uploaded_file']['tmp_name']);
             break;
         default:
             $fullImage = imagecreatefromjpeg($_FILES['uploaded_file']['tmp_name']);
             break;
     }
     $scale = 1;
     if ($fullSize[0] > $fullSize[1]) {
         $scale = $fullSize[0] / $tsetting["max_width"];
     } else {
         $scale = $fullSize[1] / $tsetting["max_height"];
     }
     $tnImage = imagecreatetruecolor($fullSize[0] / $scale, $fullSize[1] / $scale);
     imagecopyresampled($tnImage, $fullImage, 0, 0, 0, 0, $fullSize[0] / $scale, $fullSize[1] / $scale, $fullSize[0], $fullSize[1]);
     $tnImage = UnsharpMask($tnImage, 80, 0.5, 3);
     switch ($ext) {
         case "png":
             imagepng($tnImage, dirname(__FILE__) . $upload_folder . "\\" . $filen . $tsetting["suffix"] . ".png");
             break;
         case "gif":
             imagegif($tnImage, dirname(__FILE__) . $upload_folder . "\\" . $filen . $tsetting["suffix"] . ".gif");
             break;
         default:
             imagejpeg($tnImage, dirname(__FILE__) . $upload_folder . "\\" . $filen . $tsetting["suffix"] . "." . $ext);
             break;
     }
     imagedestroy($tnImage);
 } else {
     //do not create thumbs...
     $thumb_url = $final_url;
Exemple #11
0
/**
* Smarty plugin "Thumb" creates cached thumbnails
* 
* @copyright (C) 2005 Christoph Erdmann http://www.cerdmann.com/thumb/
* 
* @license This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA 
* 
* @author Christoph Erdmann (CE) http://www.cerdmann.com
* @author Benjamin Fleckenstein (BF) http://www.benjaminfleckenstein.de
* @author Marcus Gueldenmeister (MG) http://www.gueldenmeister.de/marcus/
* @author Andreas Bösch (AB)
* @author Jason Hinkle (JH) http://www.verysimple.com/
* 
* @param hint true/false to show magnifying glass overlay
* @param link true/false to link to original image
* @param extrapolate true/false to enlarge image if necessary
* @param cache file path to writable directory for cache files
* @param dev set to true to overlay the rendering time on the image
* 
* @version:
* 2012-01-05 Friendly output when file type is not supported such as pdf, swf, etc (JH)
* 2010-10-03 Friendly output when file size is empty due to unknown error (JH)
* 2008-03-13 set default param values to avoid various warnings in strict mode
             error handling when cache is not writable
             changed empty to !isset to make params work properly
             if cache path is a full uri, strip it out in the generated html code (JH)
* 2007-01-07 Friendly output when file doesn't exist and/or is blank (JH)
* 2005-10-31 Fixed some small bugs (CE)
* 2005-10-09 Rewrote crop-function (CE)
* 2005-10-08 Decreased processing time by prescaling linear and cleaned code (CE)
* 2005-07-13 Set crop=true as standard (CE)
* 2005-07-12 Added crop parameter. Original code by "djneoform at gmail dot com" (AB)
* 2005-07-02 Found a stupid mistake. Should be faster now (CE)
* 2005-06-02 Added file_exists(SOURCE)-trigger (CE)
* 2005-06-02 Added extrapolate parameter (CE)
* 2005-06-12 Bugfix alt/title (MG)
* 2005-06-10 Bugfix (MG)
* 2005-06-02 Added window parameter (MG)
* 2005-06-02 Made grey banner configurable, added possibility to keep format in thumbs
			  made cache path changeable (BF & MG)
* 2004-12-01 New link, hint, quality and type parameter (CE)
* 2004-12-02 Intergrated UnsharpMask (CE)
* -------------------------------------------------------------
*/
function smarty_function_thumb($params, &$smarty)
{
    // prevents warning in strict mode (JH)
    if (!isset($params['width'])) {
        $params['width'] = null;
    }
    if (!isset($params['height'])) {
        $params['height'] = null;
    }
    if (!isset($params['longside'])) {
        $params['longside'] = null;
    }
    if (!isset($params['shortside'])) {
        $params['shortside'] = null;
    }
    if (!isset($params['html'])) {
        $params['html'] = null;
    }
    if (!isset($params['sharpen'])) {
        $params['sharpen'] = null;
    }
    if (!isset($params['hint'])) {
        $params['hint'] = null;
    }
    if (!isset($params['addgreytohint'])) {
        $params['addgreytohint'] = null;
    }
    if (!isset($params['link'])) {
        $params['link'] = true;
    }
    if (!isset($params['window'])) {
        $params['window'] = true;
    }
    if (!isset($params['hint'])) {
        $params['hint'] = true;
    }
    if (!isset($params['extrapolate'])) {
        $params['extrapolate'] = true;
    }
    if (!isset($params['dev'])) {
        $params['dev'] = false;
    }
    if (!isset($params['crop'])) {
        $params['crop'] = true;
    }
    if (!isset($params['width']) && !isset($params['height']) && !isset($params['longside']) && !isset($params['shortside'])) {
        $params['width'] = 100;
    }
    // have a look at the params for debugging purposes
    // return "<pre>" . print_r($params,1) . "</pre>";
    // defining these prevents warnings
    $_SRC = array();
    $_DST = array();
    $_DST['offset_w'] = 0;
    $_DST['offset_h'] = 0;
    // Start time measurement
    if ($params['dev']) {
        if (!function_exists('getmicrotime')) {
            function getmicrotime()
            {
                list($usec, $sec) = explode(" ", microtime());
                return (double) $usec + (double) $sec;
            }
        }
        $time['start'] = getmicrotime();
    }
    // Funktion zum Schärfen
    if (!function_exists('UnsharpMask')) {
        // Unsharp mask algorithm by Torstein Hønsi 2003 (thoensi_at_netcom_dot_no)
        // Christoph Erdmann: changed it a little, cause i could not reproduce the darker blurred image, now it is up to 15% faster with same results
        function UnsharpMask($img, $amount, $radius, $threshold)
        {
            // Attempt to calibrate the parameters to Photoshop:
            if ($amount > 500) {
                $amount = 500;
            }
            $amount = $amount * 0.016;
            if ($radius > 50) {
                $radius = 50;
            }
            $radius = $radius * 2;
            if ($threshold > 255) {
                $threshold = 255;
            }
            $radius = abs(round($radius));
            // Only integers make sense.
            if ($radius == 0) {
                return $img;
                imagedestroy($img);
                break;
            }
            $w = imagesx($img);
            $h = imagesy($img);
            $imgCanvas = $img;
            $imgCanvas2 = $img;
            $imgBlur = imagecreatetruecolor($w, $h);
            // Gaussian blur matrix:
            //	1	2	1
            //	2	4	2
            //	1	2	1
            // Move copies of the image around one pixel at the time and merge them with weight
            // according to the matrix. The same matrix is simply repeated for higher radii.
            for ($i = 0; $i < $radius; $i++) {
                imagecopy($imgBlur, $imgCanvas, 0, 0, 1, 1, $w - 1, $h - 1);
                // up left
                imagecopymerge($imgBlur, $imgCanvas, 1, 1, 0, 0, $w, $h, 50);
                // down right
                imagecopymerge($imgBlur, $imgCanvas, 0, 1, 1, 0, $w - 1, $h, 33.33333);
                // down left
                imagecopymerge($imgBlur, $imgCanvas, 1, 0, 0, 1, $w, $h - 1, 25);
                // up right
                imagecopymerge($imgBlur, $imgCanvas, 0, 0, 1, 0, $w - 1, $h, 33.33333);
                // left
                imagecopymerge($imgBlur, $imgCanvas, 1, 0, 0, 0, $w, $h, 25);
                // right
                imagecopymerge($imgBlur, $imgCanvas, 0, 0, 0, 1, $w, $h - 1, 20);
                // up
                imagecopymerge($imgBlur, $imgCanvas, 0, 1, 0, 0, $w, $h, 16.666667);
                // down
                imagecopymerge($imgBlur, $imgCanvas, 0, 0, 0, 0, $w, $h, 50);
                // center
            }
            $imgCanvas = $imgBlur;
            // Calculate the difference between the blurred pixels and the original
            // and set the pixels
            for ($x = 0; $x < $w; $x++) {
                // each row
                for ($y = 0; $y < $h; $y++) {
                    // each pixel
                    $rgbOrig = ImageColorAt($imgCanvas2, $x, $y);
                    $rOrig = $rgbOrig >> 16 & 0xff;
                    $gOrig = $rgbOrig >> 8 & 0xff;
                    $bOrig = $rgbOrig & 0xff;
                    $rgbBlur = ImageColorAt($imgCanvas, $x, $y);
                    $rBlur = $rgbBlur >> 16 & 0xff;
                    $gBlur = $rgbBlur >> 8 & 0xff;
                    $bBlur = $rgbBlur & 0xff;
                    // When the masked pixels differ less from the original
                    // than the threshold specifies, they are set to their original value.
                    $rNew = abs($rOrig - $rBlur) >= $threshold ? max(0, min(255, $amount * ($rOrig - $rBlur) + $rOrig)) : $rOrig;
                    $gNew = abs($gOrig - $gBlur) >= $threshold ? max(0, min(255, $amount * ($gOrig - $gBlur) + $gOrig)) : $gOrig;
                    $bNew = abs($bOrig - $bBlur) >= $threshold ? max(0, min(255, $amount * ($bOrig - $bBlur) + $bOrig)) : $bOrig;
                    if ($rOrig != $rNew || $gOrig != $gNew || $bOrig != $bNew) {
                        $pixCol = ImageColorAllocate($img, $rNew, $gNew, $bNew);
                        ImageSetPixel($img, $x, $y, $pixCol);
                    }
                }
            }
            return $img;
        }
    }
    $_CONFIG['types'] = array('', '.gif', '.jpg', '.png');
    ### Übergebene Parameter auswerten und verifizieren
    if (empty($params['cache'])) {
        $_CONFIG['cache'] = 'images/cache/';
    } else {
        $_CONFIG['cache'] = $params['cache'];
    }
    //if (empty($params['file']) OR !file_exists($params['file'])) { $smarty->_trigger_fatal_error("thumb: parameter 'file' cannot be empty and must exist");	return;	}
    if (empty($params['file'])) {
        return "<div class='warning'>thumb: parameter 'file' cannot be empty is required and cannot be blank</div>";
    }
    if (!file_exists($params['file'])) {
        return "<div class='warning'>thumb: file '" . $params['file'] . "' could not be found</div>";
    }
    ### Info über Source (SRC) holen
    $temp = getimagesize($params['file']);
    $_SRC['file'] = $params['file'];
    $_SRC['width'] = $temp[0];
    $_SRC['height'] = $temp[1];
    $_SRC['type'] = $temp[2];
    // 1=GIF, 2=JPG, 3=PNG, SWF=4
    $_SRC['string'] = $temp[3];
    $_SRC['filename'] = basename($params['file']);
    $_SRC['modified'] = filemtime($params['file']);
    // Hash erstellen
    $_SRC['hash'] = md5($_SRC['file'] . $_SRC['modified'] . implode('', $params));
    if (empty($_SRC['type'])) {
        return "<div class='warning'>thumb: unsupported image type</div>";
    }
    // image types: 1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(orden de bytes intel), 8 = TIFF(orden de bytes motorola), 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC, 14 = IFF, 15 = WBMP, 16 = XBM
    if ($_SRC['type'] > 3) {
        return "<div class='warning'>thumb: image type is not supported.  supported types are GIF, JPG and PNG</div>";
    }
    ### Infos über Destination (DST) errechnen
    if (is_numeric($params['width'])) {
        $_DST['width'] = $params['width'];
    } else {
        if ($_SRC['height'] == 0 || $_SRC['width'] == 0) {
            return "<div class='warning'>thumb: illegal width/height value</div>";
        }
        $_DST['width'] = round($params['height'] / ($_SRC['height'] / $_SRC['width']));
    }
    if (is_numeric($params['height'])) {
        $_DST['height'] = $params['height'];
    } else {
        if ($_SRC['height'] == 0 || $_SRC['width'] == 0) {
            return "<div class='warning'>thumb: illegal width/height value</div>";
        }
        $_DST['height'] = round($params['width'] / ($_SRC['width'] / $_SRC['height']));
    }
    // Das Größenverhältnis soll erhalten bleiben egal ob das Bild hoch oder querformatig ist.
    if (is_numeric($params['longside'])) {
        if ($_SRC['width'] < $_SRC['height']) {
            $_DST['height'] = $params['longside'];
            $_DST['width'] = round($params['longside'] / ($_SRC['height'] / $_SRC['width']));
        } else {
            $_DST['width'] = $params['longside'];
            $_DST['height'] = round($params['longside'] / ($_SRC['width'] / $_SRC['height']));
        }
    } elseif (is_numeric($params['shortside'])) {
        if ($_SRC['width'] < $_SRC['height']) {
            $_DST['width'] = $params['shortside'];
            $_DST['height'] = round($params['shortside'] / ($_SRC['width'] / $_SRC['height']));
        } else {
            $_DST['height'] = $params['shortside'];
            $_DST['width'] = round($params['shortside'] / ($_SRC['height'] / $_SRC['width']));
        }
    }
    // Soll beschnitten werden? (Standard)
    if ($params['crop']) {
        $width_ratio = $_SRC['width'] / $_DST['width'];
        $height_ratio = $_SRC['height'] / $_DST['height'];
        // Es muss an der Breite beschnitten werden
        if ($width_ratio > $height_ratio) {
            $_DST['offset_w'] = round(($_SRC['width'] - $_DST['width'] * $height_ratio) / 2);
            $_SRC['width'] = round($_DST['width'] * $height_ratio);
        } elseif ($width_ratio < $height_ratio) {
            $_DST['offset_h'] = round(($_SRC['height'] - $_DST['height'] * $width_ratio) / 2);
            $_SRC['height'] = round($_DST['height'] * $width_ratio);
        }
    }
    // Wenn das Ursprungsbild kleiner als das Ziel-Bild ist, soll nicht hochskaliert werden und die neu berechneten Werte werden wieder überschrieben
    if ($params['extrapolate'] != true && $params['extrapolate'] != "true" && $_DST['height'] > $_SRC['height'] && $_DST['width'] > $_SRC['width']) {
        $_DST['width'] = $_SRC['width'];
        $_DST['height'] = $_SRC['height'];
    }
    if (!empty($params['type'])) {
        $_DST['type'] = $params['type'];
    } else {
        $_DST['type'] = $_SRC['type'];
    }
    //	if ( empty($_CONFIG['cache']) || empty($_SRC['hash']) || empty($_CONFIG['types']) || empty($_DST['type']))
    //	{
    //
    //	}
    $_DST['file'] = $_CONFIG['cache'] . $_SRC['hash'] . $_CONFIG['types'][$_DST['type']];
    $_DST['string'] = 'width="' . $_DST['width'] . '" height="' . $_DST['height'] . '"';
    // strip out any path stuff in case the cache path is a full URI (JH)
    $file_url = str_replace(realpath("."), ".", $_DST['file']);
    $file_url = str_replace(array("\\", "//"), array("/", "/"), $file_url);
    ### Rückgabe-Strings erstellen
    if (empty($params['html'])) {
        $_RETURN['img'] = '<img src="' . $file_url . '" ' . $params['html'] . ' ' . $_DST['string'] . ' alt="" title="" />';
    } else {
        $_RETURN['img'] = '<img src="' . $file_url . '" ' . $params['html'] . ' ' . $_DST['string'] . ' />';
    }
    if ($params['link'] == "true") {
        if (empty($params['linkurl'])) {
            $params['linkurl'] = $file_url;
        }
        if ($params['window'] == "true") {
            $returner = '<a href="' . $file_url . '" target="_blank">' . $_RETURN['img'] . '</a>';
        } else {
            $returner = '<a href="' . $file_url . '">' . $_RETURN['img'] . '</a>';
        }
    } else {
        $returner = $_RETURN['img'];
    }
    ### Cache-Datei abfangen
    if (file_exists($_DST['file']) and !$params['dev']) {
        return $returner;
    }
    ### ansonsten weitermachen
    // SRC einlesen
    if ($_SRC['type'] == 1) {
        $_SRC['image'] = imagecreatefromgif($_SRC['file']);
    }
    if ($_SRC['type'] == 2) {
        $_SRC['image'] = imagecreatefromjpeg($_SRC['file']);
    }
    if ($_SRC['type'] == 3) {
        $_SRC['image'] = imagecreatefrompng($_SRC['file']);
    }
    // Wenn das Bild sehr groß ist, zuerst linear auf vierfache Zielgröße herunterskalieren und $_SRC überschreiben
    if ($_DST['width'] * 4 < $_SRC['width'] and $_DST['height'] * 4 < $_SRC['height']) {
        // Multiplikator der Zielgröße
        $_TMP['width'] = round($_DST['width'] * 4);
        $_TMP['height'] = round($_DST['height'] * 4);
        $_TMP['image'] = imagecreatetruecolor($_TMP['width'], $_TMP['height']);
        imagecopyresized($_TMP['image'], $_SRC['image'], 0, 0, $_DST['offset_w'], $_DST['offset_h'], $_TMP['width'], $_TMP['height'], $_SRC['width'], $_SRC['height']);
        $_SRC['image'] = $_TMP['image'];
        $_SRC['width'] = $_TMP['width'];
        $_SRC['height'] = $_TMP['height'];
        // Wenn vorskaliert wird, darf ja nicht nochmal ein bestimmter Bereich ausgeschnitten werden
        $_DST['offset_w'] = 0;
        $_DST['offset_h'] = 0;
        unset($_TMP['image']);
    }
    // DST erstellen
    $_DST['image'] = imagecreatetruecolor($_DST['width'], $_DST['height']);
    imagecopyresampled($_DST['image'], $_SRC['image'], 0, 0, $_DST['offset_w'], $_DST['offset_h'], $_DST['width'], $_DST['height'], $_SRC['width'], $_SRC['height']);
    if ($params['sharpen'] != "false") {
        $_DST['image'] = UnsharpMask($_DST['image'], 80, 0.5, 3);
    }
    // Soll eine Lupe eingefügt werden?
    if ($params['hint'] == "true" and $params['link'] == "true") {
        //Soll der weiße Balken wirklich hinzugefügt werden?
        if ($params['addgreytohint'] != 'false') {
            $trans = imagecolorallocatealpha($_DST['image'], 255, 255, 255, 25);
            imagefilledrectangle($_DST['image'], 0, $_DST['height'] - 9, $_DST['width'], $_DST['height'], $trans);
        }
        $magnifier = imagecreatefromstring(gzuncompress(base64_decode("eJzrDPBz5+WS4mJgYOD19HAJAtLcIMzBBiRXrilXA1IsxU6eIRxAUMOR0gHkcxZ4RBYD1QiBMOOlu3V/gIISJa4RJc5FqYklmfl5CiGZuakMBoZ6hkZ6RgYGJs77ex2BalRBaoLz00rKE4tSGXwTk4vyc1NTMhMV3DKLUsvzi7KLFXwjFEAa2svWnGdgYPTydHEMqZhTOsE++1CAyNHzm2NZjgau+dAmXlAwoatQmOld3t/NPxlLMvY7sovPzXHf7re05BPzjpQTMkZTPjm1HlHkv6clYWK43Zt16rcDjdZ/3j2cd7qD4/HHH3GaprFrw0QZDHicORXl2JsPsveVTDz//L3N+WpxJ5Hff+10Tjdd2/Vi17vea79Om5w9zzyne9GLnWGrN8atby/ayXPOsu2w4quvVtxNCVVz5nAf3nDpZckBCedpqSc28WTOWnT7rZNXZSlPvFybie9EFc6y3bIMCn3JAoJ+kyyfn9qWq+LZ9Las26Jv482cDRE6Ci0B6gVbo2oj9KabzD8vyMK4ZMqMs2kSvW4chz88SXNzmeGjtj1QZK9M3HHL8L7HITX3t19//VVY8CYDg9Kvy2vDXu+6mGGxNOiltMPsjn/t9eJr0ja/FOdi5TyQ9Lz3fOqstOr99/dnro2vZ1jy76D/vYivPsBoYPB09XNZ55TQBAAJjs5s</body>")));
        imagealphablending($_DST['image'], true);
        imagecopy($_DST['image'], $magnifier, $_DST['width'] - 15, $_DST['height'] - 14, 0, 0, 11, 11);
        imagedestroy($magnifier);
    }
    // Berechnungszeit hinzufügen
    if ($params['dev']) {
        // Zeit anhalten
        $time['end'] = getmicrotime();
        $time = round($time['end'] - $time['start'], 2);
        // Farben definieren
        $white_trans = imagecolorallocatealpha($_DST['image'], 255, 255, 255, 25);
        $black = ImageColorAllocate($_DST['image'], 0, 0, 0);
        // Weißer Balken oben
        imagefilledrectangle($_DST['image'], 0, 0, $_DST['width'], 10, $white_trans);
        // Schrift mit Zeitangabe
        imagestring($_DST['image'], 1, 5, 2, 'processing time: ' . $time . 's', $black);
    }
    if (!is_writeable($_CONFIG['cache'])) {
        return "<div class='warning'>thumb: unable to write cache to '" . $_DST['file'] . "'  Provide a cache parameter to use an alternate location.</div>";
    }
    // Thumbnail abspeichern
    if ($_DST['type'] == 1) {
        imagetruecolortopalette($_DST['image'], false, 256);
        imagegif($_DST['image'], $_DST['file']);
    }
    if ($_DST['type'] == 2) {
        if (empty($params['quality'])) {
            $params['quality'] = 80;
        }
        imagejpeg($_DST['image'], $_DST['file'], $params['quality']);
    }
    if ($_DST['type'] == 3) {
        imagepng($_DST['image'], $_DST['file']);
    }
    imagedestroy($_DST['image']);
    imagedestroy($_SRC['image']);
    // Und Bild ausgeben
    return $returner;
}
Exemple #12
0
function j_make_image($in_name, $out_name, $sz = array(), $use_reg = true)
{
    // контекст картинки по умолчанию
    if ($use_reg) {
        if (!$GLOBALS[REG]->get_section('/system/pics', $sz_reg)) {
            set_error_ex('Unspecified picture proportions!', SYS_ERR);
            return '';
        }
        $sz = array_merge($sz_reg, $sz);
    }
    $tmp = $in_name;
    //echo $tmp.' '. file_exists($tmp);
    $inf = @getimagesize($tmp);
    if (empty($inf) || $inf[2] < 1 || $inf[2] > 3) {
        return false;
    }
    switch ($inf[2]) {
        case 1:
            $img = ImageCreateFromGIF($tmp);
            break;
        case 2:
            $img = ImageCreateFromJPEG($tmp);
            break;
        case 3:
            $img = ImageCreateFromPNG($tmp);
            break;
    }
    // prepare pic name
    if (empty($out_name) || !empty($sz['no_pic']) && $out_name == $sz['no_pic']) {
        $out_name = uniqid('img', false);
    }
    //Detect quality
    if (empty($sz['quality'])) {
        $sz['quality'] = 100;
    }
    //JOHN Генерация имен, фикс тумбнейла
    if (empty($sz['pic_nm'])) {
        $sz['pic_nm'] = '{name}';
    }
    if (empty($sz['tmb_nm'])) {
        $sz['tmb_nm'] = 'thumb_{name}';
    }
    if (!isset($sz['pic_fix'])) {
        $sz['pic_fix'] = -1;
    }
    if (!isset($sz['tmb_fix'])) {
        $sz['tmb_fix'] = -1;
    }
    if (isset($sz['unsharp']) && (int) $sz['unsharp'] < 50) {
        $sz['unsharp'] = 100;
    }
    // process  tumbnail
    $i = min($sz['tmb_x'], $sz['tmb_y']);
    if ($i > 0) {
        //Вычисление пропорций
        $dx = $inf[0] / $sz['tmb_x'];
        $dy = $inf[1] / $sz['tmb_y'];
        if ($inf[0] >= $inf[1]) {
            $pt = 'l';
        } else {
            $pt = 'p';
        }
        $sides = array('x', 'y');
        if ($sz['tmb_fix'] < 0) {
            $mpl = min($dx, $dy);
        } else {
            $mpl = $inf[$sz['tmb_fix']] / $sz['tmb_' . $sides[$sz['tmb_fix']]];
        }
        //Размеры превью
        $x = (int) $inf[0] / $mpl;
        $y = (int) $inf[1] / $mpl;
        // Создаю временные имеджи
        $tmb = ImageCreateTrueColor($x, $y);
        //$tmb=ImageCreateTrueColor($sz['tmb_x'],$sz['tmb_y']);
        if ($sz['tmb_fix'] < 0) {
            // find x,y and crop
            $px = (int) ($x - $sz['tmb_x']) / 2;
            $py = (int) ($y - $sz['tmb_y']) / 2;
        } else {
            $px = $py = 0;
        }
        // Масштабирую превью
        ImageCopyResampled($tmb, $img, 0, 0, $px, $py, $x, $y, $inf[0], $inf[1]);
        // save tumbnail
        $path = sprintf('%s/%s', $sz['path'], str_replace('{name}', $out_name, $sz['tmb_nm']) . '.jpg');
        if (!empty($sz['unsharp'])) {
            $tmb = UnsharpMask($tmb, (int) ($sz['unsharp'] * 2 / ($inf[0] / $x)), 0.5, 0);
        }
        ImageJPEG($tmb, $path, $sz['quality']);
    }
    // ПРоверка параметров
    $i = min($sz['pic_px'], $sz['pic_py'], $sz['pic_lx'], $sz['pic_ly']);
    // if -1 do nothing
    if ($i < 1) {
        return $out_name;
    }
    //Проверить, если картинка меньше чем нужно в настройке - ниче не делать
    if ($inf[0] > $inf[1]) {
        $cs = $inf[0];
        $p = 'lx';
    } else {
        $cs = $inf[1];
        $p = 'py';
    }
    //Если ничего не фиксируется и картинка меньше чем требуется - выдать как есть
    if ($sz['pic_fix'] < 0 && $cs < $sz['pic_' . $p]) {
        $i = 0;
    }
    $out_name = str_replace('{name}', $out_name, $sz['pic_nm']) . '.jpg';
    $path = sprintf('%s/%s', $sz['path'], $out_name);
    //$path=sprintf('%s/%s',$sz['path'],str_replace('{name}',$out_name,$sz['pic_nm']).'.jpg');
    if ($i > 0) {
        // resize main image
        if ($inf[0] >= $inf[1]) {
            $pt = 'l';
        } else {
            $pt = 'p';
        }
        $sides = array('x', 'y');
        //echo '<pre class="debug">'.print_r ( $inf ,true).'</pre>';
        //координыты копирования нулевые
        $px = 0;
        $py = 0;
        //Вычисление пропорций и(или) размеров результирующей картинки
        if ($sz['pic_fix'] < 0) {
            //Если не фиксировать размеры
            $mpl = max($inf[0] / $sz['pic_' . $pt . 'x'], $inf[1] / $sz['pic_' . $pt . 'y']);
            $w = $x = (int) $inf[0] / $mpl;
            $h = $y = (int) $inf[1] / $mpl;
        } else {
            $fix_both = false;
            //Если фиксировать размеры
            if ($sz['pic_fix'] == 2) {
                //Если сказано зафиксировать обе стороны - т.е. Обработка как у превью
                $fix_both = true;
                //Определяю по какой стороне приводить (должна быть меньшая)
                if ($inf[0] < $inf[1]) {
                    $sz['pic_fix'] = 0;
                } else {
                    $sz['pic_fix'] = 1;
                }
                //Вычисление пропорций ширины и высоты
                $mpl = $inf[$sz['pic_fix']] / $sz['pic_' . $pt . $sides[$sz['pic_fix']]];
                //echo '<br /> Приводить по '.$sz['pic_fix'];
                $x = (int) $sz['pic_' . $pt . 'x'];
                $y = (int) $sz['pic_' . $pt . 'y'];
                //echo "<br /> Размеры картинки $x X $y";
                //echo $inf[0].' '.$mpl;
                //Вычисление координат кропирования
                $px = (int) ($inf[0] * 0.5 - $x * 0.5 * $mpl);
                //$py=(int)($y-$sz['pic_'.$pt.'y']/2);
                $py = (int) ($inf[1] * 0.5 - $y * 0.5 * $mpl);
                //echo ' '.$px.' '.$px*$mpl;
                //echo "<br /> Кропировать $px X $py";
            } else {
                //Вычисление пропорций ширины и высоты
                $mpl = $inf[$sz['pic_fix']] / $sz['pic_' . $pt . $sides[$sz['pic_fix']]];
            }
            $w = (int) $inf[0] / $mpl;
            $h = (int) $inf[1] / $mpl;
            //Если фиксация только одной из сторон - размеры равны высоте и ширине
            if (!$fix_both) {
                $x = $w;
                $y = $h;
            }
        }
        //echo "Размер:$x X $y Высота ширина: $w X $h <br /> Начиная с: $px , $py НА {$inf[0]},{$inf[1]} ";
        $tmp_img = ImageCreateTrueColor($x, $y);
        ImageCopyResampled($tmp_img, $img, 0, 0, $px, $py, $w, $h, $inf[0], $inf[1]);
        //imagecopyresampled  ( Куда , что , х_куда  , y_куда  , x_что  , y_что  , w_куда  , h_куда  , w_что  , $h_что  )
        // save original as
        if (!empty($sz['watermark']) && file_exists($sz['watermark'])) {
            //$fh=fopen('wm_log.txt', 'w');  fwrite($fh, print_r($sz,true)); fclose($fh);
            $wm = imagecreatefrompng($sz['watermark']);
            imagecopy($tmp_img, $wm, $x * 0.5 - 200, $y - 150, 0, 0, 401, 150);
            //imagecopy($tmp_img, $wm, 0, 0, 0, 0, 401, 150); ImagePNG($wm,'tst.png');
        }
        if (!empty($sz['unsharp'])) {
            $tmp_img = UnsharpMask($tmp_img, (int) ($sz['unsharp'] / ($inf[0] / $w)), 0.5, 0);
        }
        ImageJPEG($tmp_img, $path, $sz['quality']);
    } else {
        // save main image without  resize
        ImageJPEG($img, $path, $sz['quality']);
    }
    return $out_name;
}
Exemple #13
0
 function thumbnail($type = '', $filename = '', $thumb_width = 0, $thumb_height = 0, $is_create = false, $is_crop = true, $crop_mode = 'center', $is_sharpen = false, $um_value = '80/0.5/3', $create_animate_thumb = false)
 {
     $source_file = 'uploads/';
     if ($type) {
         $source_file .= $type . '/';
     }
     $source_file .= $filename;
     if (is_file($source_file) === false) {
         // 원본 파일이 없다면
         return;
     }
     if (empty($thumb_width) && empty($thumb_height)) {
         return $source_file;
     }
     $size = @getimagesize($source_file);
     if ($size[2] < 1 or $size[2] > 3) {
         // gif, jpg, png 에 대해서만 적용
         return;
     }
     $uploadDir = 'uploads/cache/';
     if (is_dir($uploadDir) === false) {
         @mkdir($uploadDir, 0755);
         @chmod($uploadDir, 0755);
         $file = $uploadDir . 'index.php';
         $f = @fopen($file, 'w');
         @fwrite($f, '');
         @fclose($f);
         @chmod($file, 0644);
     }
     if ($type) {
         $uploadDir .= $type . '/';
         if (is_dir($uploadDir) === false) {
             @mkdir($uploadDir, 0755);
             @chmod($uploadDir, 0755);
             $file = $uploadDir . 'index.php';
             $f = @fopen($file, 'w');
             @fwrite($f, '');
             @fclose($f);
             @chmod($file, 0644);
         }
     }
     $exp = explode('/', $filename);
     $filepos = count($exp) - 1;
     for ($k = 0; $k < $filepos; $k++) {
         $uploadDir .= $exp[$k] . '/';
         if (is_dir($uploadDir) === false) {
             @mkdir($uploadDir, 0755);
             @chmod($uploadDir, 0755);
             $file = $uploadDir . 'index.php';
             $f = @fopen($file, 'w');
             @fwrite($f, '');
             @fclose($f);
             @chmod($file, 0644);
         }
     }
     $realfilename = $exp[$filepos];
     $target_path = $uploadDir;
     // 디렉토리가 존재하지 않거나 쓰기 권한이 없으면 썸네일 생성하지 않음
     if (!(is_dir($target_path) && is_writable($target_path))) {
         return '';
     }
     // Animated GIF는 썸네일 생성하지 않음
     if ($size[2] === 1) {
         if (is_animated_gif($source_file) && $create_animate_thumb === false) {
             return $source_file;
         }
     }
     $ext = array(1 => 'gif', 2 => 'jpg', 3 => 'png');
     $thumb_filename = preg_replace("/\\.[^\\.]+\$/i", '', $realfilename);
     // 확장자제거
     $thumb_file = $target_path . 'thumb-' . $thumb_filename . '_' . $thumb_width . 'x' . $thumb_height . '.' . $ext[$size[2]];
     $thumb_time = @filemtime($thumb_file);
     $source_time = @filemtime($source_file);
     if (file_exists($thumb_file)) {
         if ($is_create === false && $source_time < $thumb_time) {
             return $thumb_file;
         }
     }
     // 원본파일의 GD 이미지 생성
     $src = null;
     $degree = 0;
     if ($size[2] === 1) {
         $src = imagecreatefromgif($source_file);
         $src_transparency = imagecolortransparent($src);
     } elseif ($size[2] === 2) {
         $src = imagecreatefromjpeg($source_file);
         if (function_exists('exif_read_data')) {
             // exif 정보를 기준으로 회전각도 구함
             $exif = @exif_read_data($source_file);
             if (!empty($exif['Orientation'])) {
                 switch ($exif['Orientation']) {
                     case 8:
                         $degree = 90;
                         break;
                     case 3:
                         $degree = 180;
                         break;
                     case 6:
                         $degree = -90;
                         break;
                 }
                 // 회전각도 있으면 이미지 회전
                 if ($degree) {
                     $src = imagerotate($src, $degree, 0);
                     // 세로사진의 경우 가로, 세로 값 바꿈
                     if ($degree === 90 || $degree === -90) {
                         $tmp = $size;
                         $size[0] = $tmp[1];
                         $size[1] = $tmp[0];
                     }
                 }
             }
         }
     } elseif ($size[2] === 3) {
         $src = imagecreatefrompng($source_file);
         imagealphablending($src, true);
     } else {
         return;
     }
     if (empty($src)) {
         return;
     }
     $is_large = true;
     $keep_origin = false;
     // width, height 설정
     if ($thumb_width) {
         if (empty($thumb_height)) {
             $thumb_height = round($thumb_width * $size[1] / $size[0]);
             if ($thumb_width > $size[0]) {
                 $keep_origin = true;
             }
         } else {
             if ($size[0] < $thumb_width || $size[1] < $thumb_height) {
                 $is_large = false;
             }
         }
     } else {
         if ($thumb_height) {
             $thumb_width = round($thumb_height * $size[0] / $size[1]);
         }
     }
     $dst_x = 0;
     $dst_y = 0;
     $src_x = 0;
     $src_y = 0;
     $src_w = $size[0];
     $src_h = $size[1];
     $dst_w = $keep_origin ? $src_w : $thumb_width;
     $dst_h = $keep_origin ? $src_h : $thumb_height;
     $ratio = $dst_h / $dst_w;
     if ($is_large) {
         // 크롭처리
         if ($is_crop) {
             switch ($crop_mode) {
                 case 'center':
                     if ($size[1] / $size[0] >= $ratio) {
                         $src_h = round($src_w * $ratio);
                         $src_y = round(($size[1] - $src_h) / 2);
                     } else {
                         $src_w = round($size[1] / $ratio);
                         $src_x = round(($size[0] - $src_w) / 2);
                     }
                     break;
                 default:
                     if ($size[1] / $size[0] >= $ratio) {
                         $src_h = round($src_w * $ratio);
                     } else {
                         $src_w = round($size[1] / $ratio);
                     }
                     break;
             }
         }
         $dst = imagecreatetruecolor($dst_w, $dst_h);
         if ($size[2] === 3) {
             imagealphablending($dst, false);
             imagesavealpha($dst, true);
         } elseif ($size[2] === 1) {
             $palletsize = imagecolorstotal($src);
             if ($src_transparency >= 0 && $src_transparency < $palletsize) {
                 $transparent_color = imagecolorsforindex($src, $src_transparency);
                 $current_transparent = imagecolorallocate($dst, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
                 imagefill($dst, 0, 0, $current_transparent);
                 imagecolortransparent($dst, $current_transparent);
             }
         }
     } else {
         $dst = imagecreatetruecolor($dst_w, $dst_h);
         $bgcolor = imagecolorallocate($dst, 255, 255, 255);
         // 배경색
         if ($src_w < $dst_w) {
             if ($src_h >= $dst_h) {
                 $dst_x = round(($dst_w - $src_w) / 2);
                 $src_h = $dst_h;
             } else {
                 $dst_x = round(($dst_w - $src_w) / 2);
                 $dst_y = round(($dst_h - $src_h) / 2);
                 $dst_w = $src_w;
                 $dst_h = $src_h;
             }
         } else {
             if ($src_h < $dst_h) {
                 $dst_y = round(($dst_h - $src_h) / 2);
                 $dst_h = $src_h;
                 $src_w = $dst_w;
             }
         }
         if ($size[2] === 3) {
             $bgcolor = imagecolorallocatealpha($dst, 0, 0, 0, 127);
             imagefill($dst, 0, 0, $bgcolor);
             imagealphablending($dst, false);
             imagesavealpha($dst, true);
         } elseif ($size[2] === 1) {
             $palletsize = imagecolorstotal($src);
             if ($src_transparency >= 0 && $src_transparency < $palletsize) {
                 $transparent_color = imagecolorsforindex($src, $src_transparency);
                 $current_transparent = imagecolorallocate($dst, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
                 imagefill($dst, 0, 0, $current_transparent);
                 imagecolortransparent($dst, $current_transparent);
             } else {
                 imagefill($dst, 0, 0, $bgcolor);
             }
         } else {
             imagefill($dst, 0, 0, $bgcolor);
         }
     }
     imagecopyresampled($dst, $src, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
     // sharpen 적용
     if ($is_sharpen && $is_large) {
         $val = explode('/', $um_value);
         UnsharpMask($dst, $val[0], $val[1], $val[2]);
     }
     if ($size[2] === 1) {
         imagegif($dst, $thumb_file);
     } elseif ($size[2] === 3) {
         $png_compress = 5;
         imagepng($dst, $thumb_file, $png_compress);
     } else {
         $jpg_quality = 90;
         imagejpeg($dst, $thumb_file, $jpg_quality);
     }
     chmod($thumb_file, 0644);
     // 추후 삭제를 위하여 파일모드 변경
     imagedestroy($src);
     imagedestroy($dst);
     return $thumb_file;
 }
 function ResizeCropper($file, $dimensions, $cropinfo, &$annotation)
 {
     global $C;
     $this->PrepareImageInfo($file, $dimensions);
     $img_src = @imagecreatefromjpeg($file);
     $img_dst = @imagecreatetruecolor($this->new_width, $this->new_height);
     $img_height = imagesy($img_src);
     $img_width = imagesx($img_src);
     // Resize and crop
     @imagecopyresampled($img_dst, $img_src, 0, 0, round($cropinfo['x']), round($cropinfo['y']), $this->new_width, $this->new_height, min($img_width, $cropinfo['width']), min($img_height, $cropinfo['height']));
     @imagedestroy($img_src);
     // Apply unsharp mask
     UnsharpMask($img_dst, 60, 0.5, 2);
     // Apply the annotation
     $this->DoAnnotate($img_dst, $annotation);
     // Save the image back to disk
     @imagejpeg($img_dst, $file, $C['compression']);
 }
/**
* resize_image()
*
* Create a file containing a resized image
*
* @param  $src_file the source file
* @param  $dest_file the destination file
* @param  $new_size the size of the square within which the new image must fit
* @param  $method the method used for image resizing
* @return 'true' in case of success
*/
function resize_image($src_file, $dest_file, $new_size, $method, $thumb_use, $watermark = "false", $sharpen = 0, $media_type = "false")
{
    global $CONFIG, $ERROR;
    global $lang_errors;
    list($sharpen) = CPGPluginAPI::filter('image_sharpen', array($sharpen, $new_size));
    //Make Cage
    $superCage = Inspekt::makeSuperCage();
    $imginfo = cpg_getimagesize($src_file);
    if ($imginfo == null) {
        return false;
    }
    // GD can only handle JPG & PNG images
    if ($imginfo[2] != GIS_JPG && $imginfo[2] != GIS_PNG && $CONFIG['GIF_support'] == 0) {
        $ERROR = $lang_errors['gd_file_type_err'];
        //return false;
        return array('error' => $ERROR);
    }
    // height/width
    $srcWidth = $imginfo[0];
    $srcHeight = $imginfo[1];
    $crop = 0;
    // initialize
    // if cropping is enabled calculate cropping parameters
    if ($thumb_use == 'ex') {
        $thb_width = $CONFIG['thumb_width'];
        $thb_height = $CONFIG['thumb_height'];
        if ($new_size == $thb_width) {
            $crop = 1;
            switch ($CONFIG['thumb_method']) {
                //cropping parameters for ImageMagick
                case "im":
                    $resize_commands = "";
                    if ($srcWidth / $srcHeight > $thb_width / $thb_height) {
                        $resize_commands .= "-resize x" . $thb_height;
                        $resized_w = $thb_height / $srcHeight * $srcWidth;
                        $resize_commands .= " -crop " . $thb_width . "x" . $thb_height . "+" . round(($resized_w - $thb_width) / 2) . "+0";
                    } else {
                        $resize_commands .= "-resize " . $thb_width;
                        $resized_h = $thb_width / $srcWidth * $srcHeight;
                        $resize_commands .= " -crop " . $thb_width . "x" . $thb_height . "+0+" . round(($resized_h - $thb_height) / 2);
                    }
                    break;
                    // cropping parameters for GD2
                // cropping parameters for GD2
                default:
                    if ($srcHeight < $srcWidth) {
                        $ratio = (double) ($srcHeight / $thb_height);
                        $cpyWidth = round($thb_width * $ratio);
                        if ($cpyWidth > $srcWidth) {
                            $ratio = (double) ($srcWidth / $thb_width);
                            $cpyWidth = $srcWidth;
                            $cpyHeight = round($thb_height * $ratio);
                            $xOffset = 0;
                            $yOffset = round(($srcHeight - $cpyHeight) / 2);
                        } else {
                            $cpyHeight = $srcHeight;
                            $xOffset = round(($srcWidth - $cpyWidth) / 2);
                            $yOffset = 0;
                        }
                    } else {
                        $ratio = (double) ($srcWidth / $thb_width);
                        $cpyHeight = round($thb_height * $ratio);
                        if ($cpyHeight > $srcHeight) {
                            $ratio = (double) ($srcHeight / $thb_height);
                            $cpyHeight = $srcHeight;
                            $cpyWidth = round($thb_width * $ratio);
                            $xOffset = round(($srcWidth - $cpyWidth) / 2);
                            $yOffset = 0;
                        } else {
                            $cpyWidth = $srcWidth;
                            $xOffset = 0;
                            $yOffset = round(($srcHeight - $cpyHeight) / 2);
                        }
                    }
                    $destWidth = $thb_width;
                    $destHeight = $thb_height;
                    $srcWidth = $cpyWidth;
                    $srcHeight = $cpyHeight;
                    break;
            }
        } else {
            $ratio = max($srcWidth, $srcHeight) / $new_size;
        }
    } elseif ($thumb_use == 'wd') {
        // resize method width
        $ratio = $srcWidth / $new_size;
    } elseif ($thumb_use == 'ht') {
        // resize method height
        $ratio = $srcHeight / $new_size;
    } else {
        // resize method any
        $ratio = max($srcWidth, $srcHeight) / $new_size;
    }
    $ratio = max($ratio, 1.0);
    if ($thumb_use == 'orig') {
        $ratio = 1.0;
    }
    if ($crop != 1) {
        $destWidth = (int) ($srcWidth / $ratio);
        $destHeight = (int) ($srcHeight / $ratio);
        $resize_commands = "-geometry " . $destWidth . "x" . $destHeight;
        $xOffset = 0;
        $yOffset = 0;
    }
    // Method for thumbnails creation
    switch ($method) {
        case "im":
            if (preg_match("#[A-Z]:|\\\\#Ai", __FILE__)) {
                // get the basedir, remove '/include'
                $cur_dir = substr(dirname(__FILE__), 0, -8);
                $src_file = '"' . $cur_dir . '\\' . strtr($src_file, '/', '\\') . '"';
                $im_dest_file = str_replace('%', '%%', '"' . $cur_dir . '\\' . strtr($dest_file, '/', '\\') . '"');
            } else {
                $src_file = escapeshellarg($src_file);
                $im_dest_file = str_replace('%', '%%', escapeshellarg($dest_file));
            }
            $output = array();
            /*
             * Hack for working with ImageMagick on Windows even if IM is installed in C:\Program Files.
             * By Aditya Mooley <*****@*****.**>
             */
            if ($sharpen == 1 && $CONFIG['enable_unsharp'] == 1) {
                $unsharp_mask = " -unsharp " . $CONFIG['unsharp_radius'] . "x" . sqrt($CONFIG['unsharp_radius']) . "+" . $CONFIG['unsharp_amount'] / 100 . "+" . $CONFIG['unsharp_threshold'] / 100 . " ";
            } else {
                $unsharp_mask = "";
            }
            if ($superCage->env->getMatched('OS', '/win/i')) {
                $cmd = "\"" . str_replace("\\", "/", $CONFIG['impath']) . "convert\" -quality {$CONFIG['jpeg_qual']} {$CONFIG['im_options']} " . $resize_commands . " " . $unsharp_mask . " " . str_replace("\\", "/", $src_file) . " " . str_replace("\\", "/", $im_dest_file);
                exec("\"{$cmd}\"", $output, $retval);
            } else {
                $cmd = "{$CONFIG['impath']}convert -quality {$CONFIG['jpeg_qual']} {$CONFIG['im_options']} " . $resize_commands . " " . $unsharp_mask . " {$src_file} {$im_dest_file}";
                exec($cmd, $output, $retval);
            }
            if ($media_type != "false") {
                //if a manual thumb gets generated we watermark the thumb with the media type
                //we now need to get the absolute path to the thumb watermark files
                $path_parts = pathinfo($CONFIG['watermark_file']);
                $CONFIG['watermark_file'] = $path_parts["dirname"] . "/wm_" . $media_type . ".png";
            }
            if ($watermark == "true" || $media_type != "false") {
                //do we need to resize the watermark to fit onto the intermediate?
                $wm_normal = (int) $CONFIG['reduce_watermark'];
                if ($wm_normal > $destWidth) {
                    $wm_resize = (int) ($destWidth / $wm_normal * 100);
                    //we have to create a temporary, downsized watermark file in the edit folder
                    //temp path for small wm
                    $path_to_tmp_wm = './' . $CONFIG['fullpath'] . 'edit/temp_wm.png';
                    if ($superCage->env->getMatched('OS', '/win/i')) {
                        $cmd = "\"" . str_replace("\\", "/", $CONFIG['impath']) . "convert\" -resize " . $wm_resize . "% " . str_replace("\\", "/", $CONFIG['watermark_file']) . " " . str_replace("\\", "/", $path_to_tmp_wm);
                        exec("\"{$cmd}\"", $output, $retval);
                    } else {
                        $cmd = "{$CONFIG['impath']}convert -resize {$wm_resize}% {$CONFIG['watermark_file']} {$path_to_tmp_wm}";
                        exec($cmd, $output, $retval);
                    }
                    $wm_file = $path_to_tmp_wm;
                    //set the path to the wm file to the temp one
                } else {
                    $wm_file = $CONFIG['watermark_file'];
                    //if no downsize... we take the orig watermark
                }
                // now we apply the watermark
                if ($superCage->env->getMatched('OS', '/win/i')) {
                    $cmd = "\"" . str_replace("\\", "/", $CONFIG['impath']) . "composite\" -dissolve {$CONFIG['watermark_transparency']} -gravity {$CONFIG['where_put_watermark']} \"{$wm_file}\" " . str_replace("\\", "/", $im_dest_file) . " " . str_replace("\\", "/", $im_dest_file);
                    exec("\"{$cmd}\"", $output, $retval);
                } else {
                    $cmd = "{$CONFIG['impath']}composite -dissolve {$CONFIG['watermark_transparency']} -gravity {$CONFIG['where_put_watermark']} {$wm_file} {$im_dest_file} {$im_dest_file}";
                    exec($cmd, $output, $retval);
                }
            }
            if ($retval) {
                $ERROR = "Error executing ImageMagick - Return value: {$retval}";
                if ($CONFIG['debug_mode']) {
                    // Re-execute the command with the backtick operator in order to get all outputs
                    // will not work is safe mode is enabled
                    $output = `{$cmd} 2>&1`;
                    $ERROR .= "<br /><br /><div align=\"left\">Cmd line : <br /><span style=\"font-size:120%\">" . nl2br(htmlspecialchars($cmd)) . "</span></div>";
                    $ERROR .= "<br /><br /><div align=\"left\">The convert program said:<br /><span style=\"font-size:120%\">";
                    $ERROR .= nl2br(htmlspecialchars($output));
                    $ERROR .= "</span></div>";
                }
                @unlink($dest_file);
                return array('error' => $ERROR);
            }
            break;
        case "gd1":
            if (!function_exists('imagecreatefromjpeg')) {
                return array('error' => 'PHP running on your server does not support the GD image library, check with your webhost if ImageMagick is installed', 'halt_upload' => 1);
            }
            if ($imginfo[2] == GIS_JPG) {
                $src_img = imagecreatefromjpeg($src_file);
            } else {
                $src_img = imagecreatefrompng($src_file);
            }
            if (!$src_img) {
                $ERROR = $lang_errors['invalid_image'];
                return array('error' => $ERROR);
            }
            $dst_img = imagecreate($destWidth, $destHeight);
            imagecopyresized($dst_img, $src_img, 0, 0, $xOffset, $yOffset, (int) $destWidth, (int) $destHeight, $srcWidth, $srcHeight);
            touch($dest_file);
            $fh = fopen($dest_file, 'w');
            fclose($fh);
            imagejpeg($dst_img, $dest_file, $CONFIG['jpeg_qual']);
            imagedestroy($src_img);
            imagedestroy($dst_img);
            break;
        case "gd2":
            if (!function_exists('imagecreatefromjpeg')) {
                return array('error' => 'PHP running on your server does not support the GD image library, check with your webhost if ImageMagick is installed', 'halt_upload' => 1);
            }
            if (!function_exists('imagecreatetruecolor')) {
                return array('error' => 'PHP running on your server does not support GD version 2.x, please switch to GD version 1.x on the admin page', 'halt_upload' => 1);
            }
            if ($imginfo[2] == GIS_GIF && $CONFIG['GIF_support'] == 1) {
                $src_img = imagecreatefromgif($src_file);
            } elseif ($imginfo[2] == GIS_JPG) {
                $src_img = imagecreatefromjpeg($src_file);
            } else {
                $src_img = imagecreatefrompng($src_file);
            }
            if (!$src_img) {
                $ERROR = $lang_errors['invalid_image'];
                //return false;
                return array('error' => $ERROR);
            }
            if ($imginfo[2] == GIS_GIF) {
                $dst_img = imagecreate($destWidth, $destHeight);
            } else {
                $dst_img = imagecreatetruecolor($destWidth, $destHeight);
                if ($imginfo[2] == GIS_PNG) {
                    imagealphablending($dst_img, false);
                }
            }
            imagecopyresampled($dst_img, $src_img, 0, 0, $xOffset, $yOffset, (int) $destWidth, (int) $destHeight, $srcWidth, $srcHeight);
            touch($dest_file);
            $fh = fopen($dest_file, 'w');
            fclose($fh);
            //sharpen the thumb
            if ($sharpen == 1 && $CONFIG['enable_unsharp'] == 1) {
                UnsharpMask($dst_img, $CONFIG['unsharp_amount'], $CONFIG['unsharp_radius'], $CONFIG['unsharp_threshold']);
            }
            if ($media_type != "false") {
                //if a manual thumb gets generated we watermark the thumb with the media type
                //we now need to get the absolute path to the thumb watermark files
                $path_parts = pathinfo($CONFIG['watermark_file']);
                $CONFIG['watermark_file'] = $path_parts["dirname"] . "/wm_" . $media_type . ".png";
            }
            if ($watermark == "true" || $media_type != "false") {
                //shrink watermark on intermediate images -> If I had known that this is that �%&# with the transparency preserve... grrr
                $wm_normal = (int) $CONFIG['reduce_watermark'];
                if ($wm_normal > $destWidth) {
                    $wm_resize = $destWidth / $wm_normal;
                    //load the original, huge sized logo (the one we want to size down)
                    $temp_logoImage = ImageCreateFromPNG($CONFIG['watermark_file']);
                    //get it's size
                    $temp_logoW = ImageSX($temp_logoImage);
                    $temp_logoH = ImageSY($temp_logoImage);
                    //calculate new size
                    $logoW = (int) ($temp_logoW * $wm_resize);
                    $logoH = (int) ($temp_logoH * $wm_resize);
                    //we create a new, resized logo
                    $logoImage = imagecreatetruecolor($logoW, $logoH);
                    //just to be sure that transparency gets preserved
                    imagealphablending($logoImage, FALSE);
                    imagealphablending($temp_logoImage, TRUE);
                    //now copy and resize the big one into the temp resized img
                    imagecopyresampled($logoImage, $temp_logoImage, 0, 0, 0, 0, (int) $logoW, (int) $logoH, $temp_logoW, $temp_logoH);
                    //we do not need the temp (huge) watermark anymore
                    imagedestroy($temp_logoImage);
                } else {
                    // shrink not enabled or no intermediate...
                    $logoImage = ImageCreateFromPNG($CONFIG['watermark_file']);
                    $logoW = ImageSX($logoImage);
                    $logoH = ImageSY($logoImage);
                }
                //where is the watermark displayed...
                $pos = $CONFIG['where_put_watermark'];
                if ($pos == "northwest") {
                    $src_x = 5;
                    $src_y = 5;
                } else {
                    if ($pos == "northeast") {
                        $src_x = $destWidth - ($logoW + 5);
                        $src_y = 5;
                    } else {
                        if ($pos == "southwest") {
                            $src_x = 5;
                            $src_y = $destHeight - ($logoH + 5);
                        } else {
                            if ($pos == "southeast") {
                                $src_x = $destWidth - ($logoW + 5);
                                $src_y = $destHeight - ($logoH + 5);
                            } else {
                                if ($pos == "center") {
                                    $src_x = $destWidth / 2 - $logoW / 2;
                                    $src_y = $destHeight / 2 - $logoH / 2;
                                }
                            }
                        }
                    }
                }
                imagealphablending($dst_img, TRUE);
                imagecolortransparent($logoImage, imagecolorat($logoImage, $CONFIG['watermark_transparency_featherx'], $CONFIG['watermark_transparency_feathery']));
                ImageCopy($dst_img, $logoImage, $src_x, $src_y, 0, 0, $logoW, $logoH);
            }
            if ($imginfo[2] == GIS_PNG) {
                imagesavealpha($dst_img, true);
                imagepng($dst_img, $dest_file, round((100 - $CONFIG['jpeg_qual']) / 10));
            } else {
                imagejpeg($dst_img, $dest_file, $CONFIG['jpeg_qual']);
            }
            imagedestroy($src_img);
            imagedestroy($dst_img);
            break;
    }
    // Set mode of uploaded picture
    @chmod($dest_file, octdec($CONFIG['default_file_mode']));
    //silence the output in case chmod is disabled
    // We check that the image is valid
    $imginfo = cpg_getimagesize($dest_file);
    if ($imginfo == null) {
        $ERROR = $lang_errors['resize_failed'];
        @unlink($dest_file);
        //return false;
        return array('error' => $ERROR);
    } else {
        return true;
    }
}
 function ImageEditor($filename = 0, $path = 0, $col = NULL, $settings = '', $is_remote = true)
 {
     if ($settings == '') {
         $settings = get_option('post_thumbnail_settings');
     }
     $this->unsharp = $settings['unsharp'] == 'true';
     // Load options
     if ($settings['unsharp_amount'] == 0) {
         $this->unsharp_amount = 80;
     } else {
         $this->unsharp_amount = $settings['unsharp_amount'];
     }
     if ($settings['unsharp_radius'] == 0) {
         $this->unsharp_radius = 0.5;
     } else {
         $this->unsharp_radius = $settings['unsharp_radius'];
     }
     if ($settings['unsharp_threshold'] == 0) {
         $this->unsharp_threshold = 3;
     } else {
         $this->unsharp_threshold = $settings['unsharp_threshold'];
     }
     if ($settings['corner_ratio'] == 0) {
         $this->corner_ratio = 0.15;
     } else {
         $this->corner_ratio = $settings['corner_ratio'];
     }
     unset($settings);
     $this->font = false;
     $this->error = false;
     $this->size = 15;
     // If no image specified create blank image
     if (is_numeric($filename) && is_numeric($path)) {
         $this->x = $filename;
         $this->y = $path;
         $this->type = "jpg";
         $this->img = imagecreatetruecolor($this->x, $this->y);
         // Set background colour of image
         if (is_array($col)) {
             $colour = ImageColorAllocate($this->img, $col[0], $col[1], $col[2]);
             ImageFill($this->img, 0, 0, $colour);
         }
     } else {
         // First see if we can find image
         if (remote_file_exists($path . $filename)) {
             $file = $path . $filename;
         } else {
             if (remote_file_exists($path . "/" . $filename)) {
                 $file = $path . "/" . $filename;
             } else {
                 $this->errorImage("File Could Not Be Loaded");
             }
         }
         if (!$this->error) {
             // Load our image with correct function
             $this->type = end(explode('.', $filename));
             if ($this->type == '' || !in_array($this->type, $this->exttype)) {
                 $this->type = 'jpg';
             }
             if (is_cURL() && $is_remote) {
                 if ($tmpimg = ImageCreateFromcURL($file)) {
                     $this->img_error = false;
                 } else {
                     $this->img_error = true;
                 }
             } elseif ($this->type == 'jpg' || $this->type == 'jpeg') {
                 if (setMemoryForImage($file)) {
                     if ($tmpimg = @imagecreatefromjpeg($file)) {
                         $this->img_error = false;
                     } else {
                         $this->img_error = true;
                     }
                 } else {
                     $this->img_error = true;
                 }
             } elseif ($this->type == 'png') {
                 if (setMemoryForImage($file)) {
                     if ($tmpimg = @imagecreatefrompng($file)) {
                         $this->img_error = false;
                     } else {
                         $this->img_error = true;
                     }
                 } else {
                     $this->img_error = true;
                 }
             } elseif ($this->type == 'gif') {
                 if (setMemoryForImage($file)) {
                     if ($tmpimg = @imagecreatefromgif($file)) {
                         $this->img_error = false;
                     } else {
                         $this->img_error = true;
                     }
                 } else {
                     $this->img_error = true;
                 }
             } else {
                 if (setMemoryForImage($file)) {
                     $tmpimg = ImageCreateFromgetContents($file);
                     if ($tmpimg === false) {
                         $this->img_error = false;
                     } else {
                         $this->img_error = true;
                     }
                 } else {
                     $this->img_error = true;
                 }
             }
             // Set our image variables
             if (!$this->img_error) {
                 if ($this->unsharp) {
                     $this->img = UnsharpMask($tmpimg, $this->unsharp_amount, $this->unsharp_radius, $this->unsharp_threshold);
                 } else {
                     $this->img = $tmpimg;
                 }
                 $this->x = imageSX($this->img);
                 $this->y = imageSY($this->img);
             }
         }
     }
 }
Exemple #17
0
 /**
  * Writes a thumbnail file.
  *
  * @param  string $infile  Image file name.
  * @param  array  $outfile Array of thumb file names (1...n)
  * @return bool TRUE on success
  */
 public function write($infile, $outfile)
 {
     global $verbose;
     if ($verbose) {
         echo "writing thumb nail...";
     }
     // Get source image info.
     $temp = getimagesize($infile);
     $this->_SRC['file'] = $infile;
     $this->_SRC['width'] = $temp[0];
     $this->_SRC['height'] = $temp[1];
     $this->_SRC['type'] = $temp[2];
     // 1=GIF, 2=JPG, 3=PNG, SWF=4.
     $this->_SRC['string'] = $temp[3];
     $this->_SRC['filename'] = basename($infile);
     //$this->_SRC['modified'] = filemtime($infile);
     // Check image orientation.
     if ($this->_SRC['width'] >= $this->_SRC['height']) {
         $this->_SRC['format'] = 'landscape';
     } else {
         $this->_SRC['format'] = 'portrait';
     }
     // Get destination image info.
     if (is_numeric($this->width) and empty($this->height)) {
         $this->_DST['width'] = $this->width;
         $this->_DST['height'] = round($this->width / ($this->_SRC['width'] / $this->_SRC['height']));
     } elseif (is_numeric($this->height) and empty($this->width)) {
         $this->_DST['height'] = $this->height;
         $this->_DST['width'] = round($this->height / ($this->_SRC['height'] / $this->_SRC['width']));
     } elseif (is_numeric($this->width) and is_numeric($this->height)) {
         $this->_DST['width'] = $this->width;
         $this->_DST['height'] = $this->height;
     } elseif (is_numeric($this->longside) and empty($this->shortside)) {
         // Preserve aspect ratio based on provided height.
         if ($this->_SRC['format'] == 'portrait') {
             $this->_DST['height'] = $this->longside;
             $this->_DST['width'] = round($this->longside / ($this->_SRC['height'] / $this->_SRC['width']));
         } else {
             $this->_DST['width'] = $this->longside;
             $this->_DST['height'] = round($this->longside / ($this->_SRC['width'] / $this->_SRC['height']));
         }
     } elseif (is_numeric($this->shortside)) {
         // Preserve aspect ratio based on provided width.
         if ($this->_SRC['format'] == 'portrait') {
             $this->_DST['width'] = $this->shortside;
             $this->_DST['height'] = round($this->shortside / ($this->_SRC['width'] / $this->_SRC['height']));
         } else {
             $this->_DST['height'] = $this->shortside;
             $this->_DST['width'] = round($this->shortside / ($this->_SRC['height'] / $this->_SRC['width']));
         }
     } else {
         // Default dimensions.
         $this->width = 100;
         $this->_DST['width'] = $this->width;
         $this->_DST['height'] = round($this->width / ($this->_SRC['width'] / $this->_SRC['height']));
     }
     // Don't make the new image larger than the original image.
     if ($this->extrapolate === false && $this->_DST['height'] > $this->_SRC['height'] && $this->_DST['width'] > $this->_SRC['width']) {
         $this->_DST['width'] = $this->_SRC['width'];
         $this->_DST['height'] = $this->_SRC['height'];
     }
     $this->_DST['type'] = $this->_SRC['type'];
     $this->_DST['file'] = $outfile;
     // Make sure we have enough memory if the image is large.
     if (max($this->_SRC['width'], $this->_SRC['height']) > 1024) {
         $shorthand = array('K', 'M', 'G');
         $tens = array('000', '000000', '000000000');
         // A good enough decimal approximation of K, M, and G.
         // Do not *decrease* memory_limit.
         list($ml, $extra) = str_ireplace($shorthand, $tens, array(ini_get('memory_limit'), EXTRA_MEMORY));
         if ($ml < $extra) {
             ini_set('memory_limit', EXTRA_MEMORY);
         }
     }
     // Read source image.
     if ($this->_SRC['type'] == 1) {
         $this->_SRC['image'] = imagecreatefromgif($this->_SRC['file']);
     } elseif ($this->_SRC['type'] == 2) {
         $this->_SRC['image'] = imagecreatefromjpeg($this->_SRC['file']);
     } elseif ($this->_SRC['type'] == 3) {
         $this->_SRC['image'] = imagecreatefrompng($this->_SRC['file']);
     }
     // Crop image.
     $off_w = 0;
     $off_h = 0;
     if ($this->crop != false) {
         if ($this->_SRC['height'] < $this->_SRC['width']) {
             $ratio = (double) ($this->_SRC['height'] / $this->_DST['height']);
             $cpyWidth = round($this->_DST['width'] * $ratio);
             if ($cpyWidth > $this->_SRC['width']) {
                 $ratio = (double) ($this->_SRC['width'] / $this->_DST['width']);
                 $cpyWidth = $this->_SRC['width'];
                 $cpyHeight = round($this->_DST['height'] * $ratio);
                 $off_w = 0;
                 $off_h = round(($this->_SRC['height'] - $cpyHeight) / 2);
                 $this->_SRC['height'] = $cpyHeight;
             } else {
                 $cpyHeight = $this->_SRC['height'];
                 $off_w = round(($this->_SRC['width'] - $cpyWidth) / 2);
                 $off_h = 0;
                 $this->_SRC['width'] = $cpyWidth;
             }
         } else {
             $ratio = (double) ($this->_SRC['width'] / $this->_DST['width']);
             $cpyHeight = round($this->_DST['height'] * $ratio);
             if ($cpyHeight > $this->_SRC['height']) {
                 $ratio = (double) ($this->_SRC['height'] / $this->_DST['height']);
                 $cpyHeight = $this->_SRC['height'];
                 $cpyWidth = round($this->_DST['width'] * $ratio);
                 $off_w = round(($this->_SRC['width'] - $cpyWidth) / 2);
                 $off_h = 0;
                 $this->_SRC['width'] = $cpyWidth;
             } else {
                 $cpyWidth = $this->_SRC['width'];
                 $off_w = 0;
                 $off_h = round(($this->_SRC['height'] - $cpyHeight) / 2);
                 $this->_SRC['height'] = $cpyHeight;
             }
         }
     }
     // Ensure non-zero height/width.
     if (!$this->_DST['height']) {
         $this->_DST['height'] = 1;
     }
     if (!$this->_DST['width']) {
         $this->_DST['width'] = 1;
     }
     // Create DST.
     $this->_DST['image'] = imagecreatetruecolor($this->_DST['width'], $this->_DST['height']);
     // GIF or PNG destination, set the transparency up.
     if ($this->_DST['type'] == 1 || $this->_DST['type'] == 3) {
         $trans_idx = imagecolortransparent($this->_SRC['image']);
         // Is there a specific transparent colour?
         if ($trans_idx >= 0) {
             $trans_color = imagecolorsforindex($this->_SRC['image'], $trans_idx);
             $trans_idx = imagecolorallocate($this->_DST['image'], $trans_color['red'], $trans_color['green'], $trans_color['blue']);
             imagefill($this->_DST['image'], 0, 0, $trans_idx);
             imagecolortransparent($this->_DST['image'], $trans_idx);
         } elseif ($this->_DST['type'] == 3) {
             imagealphablending($this->_DST['image'], false);
             $transparent = imagecolorallocatealpha($this->_DST['image'], 0, 0, 0, 127);
             imagefill($this->_DST['image'], 0, 0, $transparent);
             imagesavealpha($this->_DST['image'], true);
         }
     }
     imagecopyresampled($this->_DST['image'], $this->_SRC['image'], 0, 0, $off_w, $off_h, $this->_DST['width'], $this->_DST['height'], $this->_SRC['width'], $this->_SRC['height']);
     if ($this->sharpen === true) {
         $this->_DST['image'] = UnsharpMask($this->_DST['image'], 80, 0.5, 3);
     }
     // Finally, the real dimensions.
     $this->height = $this->_DST['height'];
     $this->width = $this->_DST['width'];
     // Add magnifying glass.
     if ($this->hint === true) {
         // Should we really add white bars?
         if ($this->addgreytohint === true) {
             $trans = imagecolorallocatealpha($this->_DST['image'], 255, 255, 255, 25);
             imagefilledrectangle($this->_DST['image'], 0, $this->_DST['height'] - 9, $this->_DST['width'], $this->_DST['height'], $trans);
         }
         $magnifier = imagecreatefromstring(gzuncompress(base64_decode("eJzrDPBz5+WS4mJgYOD19HAJAtLcIMzBBiRXrilXA1IsxU6eIRxAUMOR0gHkcxZ4RBYD1QiBMOOlu3V/gIISJa4RJc5FqYklmfl5CiGZuakMBoZ6hkZ6RgYGJs77ex2BalRBaoLz00rKE4tSGXwTk4vyc1NTMhMV3DKLUsvzi7KLFXwjFEAa2svWnGdgYPTydHEMqZhTOsE++1CAyNHzm2NZjgau+dAmXlAwoatQmOld3t/NPxlLMvY7sovPzXHf7re05BPzjpQTMkZTPjm1HlHkv6clYWK43Zt16rcDjdZ/3j2cd7qD4/HHH3GaprFrw0QZDHicORXl2JsPsveVTDz//L3N+WpxJ5Hff+10Tjdd2/Vi17vea79Om5w9zzyne9GLnWGrN8atby/ayXPOsu2w4quvVtxNCVVz5nAf3nDpZckBCedpqSc28WTOWnT7rZNXZSlPvFybie9EFc6y3bIMCn3JAoJ+kyyfn9qWq+LZ9Las26Jv482cDRE6Ci0B6gVbo2oj9KabzD8vyMK4ZMqMs2kSvW4chz88SXNzmeGjtj1QZK9M3HHL8L7HITX3t19//VVY8CYDg9Kvy2vDXu+6mGGxNOiltMPsjn/t9eJr0ja/FOdi5TyQ9Lz3fOqstOr99/dnro2vZ1jy76D/vYivPsBoYPB09XNZ55TQBAAJjs5s</body>")));
         imagealphablending($this->_DST['image'], true);
         imagecopy($this->_DST['image'], $magnifier, $this->_DST['width'] - 15, $this->_DST['height'] - 14, 0, 0, 11, 11);
         imagedestroy($magnifier);
     }
     if ($verbose) {
         echo "... saving image ...";
     }
     if ($this->_DST['type'] == 1) {
         imagetruecolortopalette($this->_DST['image'], false, 256);
         if (function_exists('imagegif')) {
             imagegif($this->_DST['image'], $this->_DST['file']);
         } else {
             imagedestroy($this->_DST['image']);
             imagedestroy($this->_SRC['image']);
             return false;
         }
     } elseif ($this->_DST['type'] == 2) {
         imagejpeg($this->_DST['image'], $this->_DST['file'], $this->quality);
     } elseif ($this->_DST['type'] == 3) {
         imagepng($this->_DST['image'], $this->_DST['file']);
     }
     if ($verbose) {
         echo "... image successfully saved ...";
     }
     imagedestroy($this->_DST['image']);
     imagedestroy($this->_SRC['image']);
     return true;
 }
 /**
  * general purpose internal method for creating resized images - accepts
  * a variety of options. Use this to build specific methods for public
  * consumption
  * 
  * maxw : maximum width of image (default '100')
  * maxh : maximum height of image (default '100')
  * bestfit : show entire image inside max width/height. If false
  *           then the image is cropped to match the aspect ratio of
  *           of the target area first (default 'true')
  * attribname : attribute name of img tag which holds url (default 'src')
  * bevel : give image a raised edge (default true)
  * unsharp : do an unsharp mask on the image
  * pano : do not crop, even if w:h > 2:1 (default false)
  * 
  * returns an association array containing 'html' element, which contains
  * a fragment to load the image, and 'path' containg relative url to image
  */
 function _getResized($params)
 {
     global $memcache, $CONF, $MESSAGES;
     $mkey = "{$this->gridimage_id}:" . md5(serialize($params));
     //fails quickly if not using memcached!
     $result =& $memcache->name_get('ir', $mkey);
     if ($result && $result['url'] != '/photos/error.jpg') {
         return $result;
     }
     //unpack known params and set defaults
     $maxw = isset($params['maxw']) ? $params['maxw'] : 100;
     $maxh = isset($params['maxh']) ? $params['maxh'] : 100;
     $attribname = isset($params['attribname']) ? $params['attribname'] : 'src';
     $bestfit = isset($params['bestfit']) ? $params['bestfit'] : true;
     $bevel = isset($params['bevel']) ? $params['bevel'] : true;
     $unsharp = isset($params['unsharp']) ? $params['unsharp'] : true;
     $pano = isset($params['pano']) ? $params['pano'] : false;
     $source = isset($params['source']) ? $params['source'] : '';
     global $CONF;
     //establish whether we have a cached thumbnail
     $ab = sprintf("%02d", floor($this->gridimage_id % 1000000 / 10000));
     $cd = sprintf("%02d", floor($this->gridimage_id % 10000 / 100));
     $abcdef = sprintf("%06d", $this->gridimage_id);
     $hash = $this->_getAntiLeechHash();
     $base = $_SERVER['DOCUMENT_ROOT'] . '/photos';
     if ($this->gridimage_id < 1000000) {
         $thumbpath = "/photos/{$ab}/{$cd}/{$abcdef}_{$hash}_{$maxw}x{$maxh}.jpg";
     } else {
         $yz = sprintf("%02d", floor($this->gridimage_id / 1000000));
         $thumbpath = "/geophotos/{$yz}/{$ab}/{$cd}/{$abcdef}_{$hash}_{$maxw}x{$maxh}.jpg";
     }
     if (!empty($params['urlonly']) && $params['urlonly'] !== 2 && file_exists($_SERVER['DOCUMENT_ROOT'] . $thumbpath)) {
         $return = array();
         $return['url'] = $thumbpath;
         if (!empty($CONF['enable_cluster'])) {
             $return['server'] = str_replace('0', $this->gridimage_id % $CONF['enable_cluster'], "http://{$CONF['STATIC_HOST']}");
         } else {
             $return['server'] = "http://" . $CONF['CONTENT_HOST'];
         }
         return $return;
     }
     $mkey = "{$this->gridimage_id}:{$maxw}x{$maxh}";
     //fails quickly if not using memcached!
     $size =& $memcache->name_get('is', $mkey);
     if ($size) {
         $return = array();
         $return['url'] = $thumbpath;
         $by = $MESSAGES['class_gridimage']['by'];
         $title = $this->grid_reference . ' : ' . htmlentities2($this->title) . $by . htmlentities2($this->realname);
         if (!empty($CONF['enable_cluster'])) {
             $return['server'] = str_replace('0', $this->gridimage_id % $CONF['enable_cluster'], "http://{$CONF['STATIC_HOST']}");
         } else {
             $return['server'] = "http://" . $CONF['CONTENT_HOST'];
         }
         $thumbpath = $return['server'] . $thumbpath;
         if (isset($CONF['curtail_level']) && $CONF['curtail_level'] > 1 && empty($GLOBALS['USER']->user_id) && isset($GLOBALS['smarty'])) {
             $thumbpath = cachize_url($thumbpath);
         }
         $html = "<img alt=\"{$title}\" {$attribname}=\"{$thumbpath}\" {$size[3]} />";
         $return['html'] = $html;
         return $return;
     }
     if (!file_exists($_SERVER['DOCUMENT_ROOT'] . $thumbpath)) {
         if ($source == 'original') {
             $fullpath = $this->_getOriginalpath();
         } else {
             //get path to fullsize image (will try to fetch it from fetch_on_demand)
             $fullpath = $this->_getFullpath();
         }
         if ($pano && $fullpath != '/photos/error.jpg' && file_exists($_SERVER['DOCUMENT_ROOT'] . $fullpath)) {
             require_once "geograph/uploadmanager.class.php";
             $uploadmanager = new UploadManager();
             list($owidth, $oheight, $otype, $oattr) = getimagesize($_SERVER['DOCUMENT_ROOT'] . $fullpath);
             list($destwidth, $destheight, $destdim, $changedim) = $uploadmanager->_new_size($owidth, $oheight, $maxw);
             $maxw = $destdim;
             $maxh = $destdim;
             $bestfit = true;
         }
         if ($fullpath != '/photos/error.jpg' && file_exists($_SERVER['DOCUMENT_ROOT'] . $fullpath)) {
             if (strlen($CONF['imagemagick_path'])) {
                 if (($info = getimagesize($_SERVER['DOCUMENT_ROOT'] . $fullpath)) === FALSE) {
                     //couldn't read image!
                     $thumbpath = "/photos/error.jpg";
                 } else {
                     list($width, $height, $type, $attr) = $info;
                     if ($width > $maxw || $height > $maxh || !$bestfit) {
                         $unsharpen = $unsharp ? "-unsharp 0x1+0.8+0.1" : "";
                         $raised = $bevel ? "-raise 2x2" : "";
                         $operation = $maxw + $maxh < 400 ? 'thumbnail' : 'resize';
                         $aspect_src = $width / $height;
                         $aspect_dest = $maxw / $maxh;
                         if (!$pano && $bestfit && $aspect_src > 2 && $aspect_dest < 2) {
                             $bestfit = false;
                             $maxh = round($maxw / 2);
                             $aspect_dest = 2;
                         }
                         if ($bestfit) {
                             $cmd = sprintf("\"%sconvert\" -{$operation} %ldx%ld  {$unsharpen} {$raised} -quality 87 jpg:%s jpg:%s", $CONF['imagemagick_path'], $maxw, $maxh, $_SERVER['DOCUMENT_ROOT'] . $fullpath, $_SERVER['DOCUMENT_ROOT'] . $thumbpath);
                             passthru($cmd);
                         } else {
                             if ($aspect_src > $aspect_dest) {
                                 //src image is relatively wider - we'll trim the sides
                                 $optimum_width = round($height * $aspect_dest);
                                 $offset = round(($width - $optimum_width) / 2);
                                 $crop = "-crop {$optimum_width}x{$height}+{$offset}+0";
                             } else {
                                 //src image is relatively taller - we'll trim the top/bottom
                                 $optimum_height = round($width / $aspect_dest);
                                 $offset = round(($height - $optimum_height) / 2);
                                 $crop = "-crop {$width}x{$optimum_height}+0+{$offset}";
                             }
                             $cmd = sprintf("\"%sconvert\" {$crop} -quality 87 jpg:%s jpg:%s", $CONF['imagemagick_path'], $_SERVER['DOCUMENT_ROOT'] . $fullpath, $_SERVER['DOCUMENT_ROOT'] . $thumbpath);
                             passthru($cmd);
                             //now resize // FIXME: one step!
                             $cmd = sprintf("\"%smogrify\" -{$operation} %ldx%ld {$unsharpen} {$raised} -quality 87 jpg:%s", $CONF['imagemagick_path'], $maxw, $maxh, $_SERVER['DOCUMENT_ROOT'] . $thumbpath);
                             passthru($cmd);
                         }
                     } else {
                         //requested thumb is larger than original - stick with original
                         copy($_SERVER['DOCUMENT_ROOT'] . $fullpath, $_SERVER['DOCUMENT_ROOT'] . $thumbpath);
                     }
                 }
             } else {
                 // FIXME not the same as above
                 //generate resized image
                 $fullimg = @imagecreatefromjpeg($_SERVER['DOCUMENT_ROOT'] . $fullpath);
                 if ($fullimg) {
                     $srcw = imagesx($fullimg);
                     $srch = imagesy($fullimg);
                     if ($srcw > $maxw || $srch > $maxh) {
                         //figure out size of image we'll keep
                         if ($srcw > $srch) {
                             //landscape
                             $destw = $maxw;
                             $desth = round($destw * $srch / $srcw);
                         } else {
                             //portrait
                             $desth = $maxh;
                             $destw = round($desth * $srcw / $srch);
                         }
                         $resized = imagecreatetruecolor($destw, $desth);
                         imagecopyresampled($resized, $fullimg, 0, 0, 0, 0, $destw, $desth, $srcw, $srch);
                         if ($unsharp) {
                             require_once 'geograph/image.inc.php';
                             UnsharpMask($resized, 100, 0.5, 3);
                         }
                         imagedestroy($fullimg);
                         //save the thumbnail
                         imagejpeg($resized, $_SERVER['DOCUMENT_ROOT'] . $thumbpath, 85);
                         imagedestroy($resized);
                     } elseif ($srcw == 0 && $srch == 0) {
                         //couldn't read image!
                         $thumbpath = "/photos/error.jpg";
                         imagedestroy($fullimg);
                     } else {
                         //requested thumb is larger than original - stick with original
                         copy($_SERVER['DOCUMENT_ROOT'] . $fullpath, $_SERVER['DOCUMENT_ROOT'] . $thumbpath);
                     }
                 } else {
                     //couldn't load full jpeg
                     $thumbpath = "/photos/error.jpg";
                 }
             }
         } else {
             //no original image! - return link to error image
             $thumbpath = "/photos/error.jpg";
         }
     }
     $return = array();
     $return['url'] = $thumbpath;
     if ($thumbpath == '/photos/error.jpg') {
         $html = "<img {$attribname}=\"{$thumbpath}\" width=\"{$maxw}\" height=\"{$maxh}\" />";
     } else {
         $by = $MESSAGES['class_gridimage']['by'];
         $title = $this->grid_reference . ' : ' . htmlentities2($this->title) . $by . htmlentities2($this->realname);
         $size = getimagesize($_SERVER['DOCUMENT_ROOT'] . $thumbpath);
         if (!empty($CONF['enable_cluster'])) {
             $return['server'] = str_replace('0', $this->gridimage_id % $CONF['enable_cluster'], "http://{$CONF['STATIC_HOST']}");
         } else {
             $return['server'] = "http://" . $CONF['CONTENT_HOST'];
         }
         $thumbpath = $return['server'] . $thumbpath;
         if (isset($CONF['curtail_level']) && $CONF['curtail_level'] > 1 && empty($GLOBALS['USER']->user_id) && isset($GLOBALS['smarty'])) {
             $thumbpath = cachize_url($thumbpath);
         }
         $html = "<img alt=\"{$title}\" {$attribname}=\"{$thumbpath}\" {$size[3]} />";
         //fails quickly if not using memcached!
         $memcache->name_set('is', $mkey, $size, $memcache->compress, $memcache->period_med);
     }
     $return['html'] = $html;
     return $return;
 }