Esempio n. 1
0
 public function saveImg($path)
 {
     // Resize
     if ($this->resize) {
         $this->output = ImageCreateTrueColor($this->xOutput, $this->yOutput);
         ImageCopyResampled($this->output, $this->input, 0, 0, 0, 0, $this->xOutput, $this->yOutput, $this->xInput, $this->yInput);
     }
     // Save JPEG
     if ($this->format == "JPG" or $this->format == "JPEG") {
         if ($this->resize) {
             imageJPEG($this->output, $path, $this->quality);
         } else {
             copy($this->src, $path);
         }
     } elseif ($this->format == "PNG") {
         if ($this->resize) {
             imagePNG($this->output, $path);
         } else {
             copy($this->src, $path);
         }
     } elseif ($this->format == "GIF") {
         if ($this->resize) {
             imageGIF($this->output, $path);
         } else {
             copy($this->src, $path);
         }
     }
 }
function thumbnail($PicPathIn, $PicPathOut, $PicFilenameIn, $PicFilenameOut, $neueHoehe, $Quality)
{
    // Bilddaten ermitteln
    $size = getimagesize("{$PicPathIn}" . "{$PicFilenameIn}");
    $breite = $size[0];
    $hoehe = $size[1];
    $neueBreite = intval($breite * $neueHoehe / $hoehe);
    if ($size[2] == 1) {
        // GIF
        $altesBild = ImageCreateFromGIF("{$PicPathIn}" . "{$PicFilenameIn}");
        $neuesBild = imageCreateTrueColor($neueBreite, $neueHoehe);
        imageCopyResized($neuesBild, $altesBild, 0, 0, 0, 0, $neueBreite, $neueHoehe, $breite, $hoehe);
        imageJPEG($neuesBild, "{$PicPathOut}" . "{$PicFilenameOut}", $Quality);
    }
    if ($size[2] == 2) {
        // JPG
        $altesBild = ImageCreateFromJPEG("{$PicPathIn}" . "{$PicFilenameIn}");
        $neuesBild = imageCreateTrueColor($neueBreite, $neueHoehe);
        imageCopyResized($neuesBild, $altesBild, 0, 0, 0, 0, $neueBreite, $neueHoehe, $breite, $hoehe);
        ImageJPEG($neuesBild, "{$PicPathOut}" . "{$PicFilenameOut}", $Quality);
    }
    if ($size[2] == 3) {
        // PNG
        $altesBild = ImageCreateFromPNG("{$PicPathIn}" . "{$PicFilenameIn}");
        $neuesBild = imageCreateTrueColor($neueBreite, $neueHoehe);
        imageCopyResized($neuesBild, $altesBild, 0, 0, 0, 0, $neueBreite, $neueHoehe, $breite, $hoehe);
        ImageJPEG($neuesBild, "{$PicPathOut}" . "{$PicFilenameOut}", $Quality);
    }
}
Esempio n. 3
0
 public function write($path, $quality, $format = 'jpg')
 {
     if (!$this->image) {
         return false;
     }
     if ($format === 'png') {
         imagePNG($this->image, $path);
     } else {
         imageJPEG($this->image, $path, $quality);
     }
     return true;
 }
Esempio n. 4
0
 public function createThumbs($thumb_size)
 {
     $thumb = imageCreateTrueColor($thumb_size['width'], $thumb_size['height']);
     if ($thumb === false) {
         throw new Exception('cannot create img_thumb file');
     }
     $resX = floor(imagesx($this->_orig_img) * ($thumb_size['height'] / imagesy($this->_orig_img)));
     $resY = $thumb_size['height'];
     imageAntiAlias($thumb, true);
     imagecopyresized($thumb, $this->_orig_img, 0, 0, 0, 0, $resX, $resY, imagesx($this->_orig_img), imagesy($this->_orig_img));
     if (!imageJPEG($thumb, $this->_save_path . 'thumbs_' . $this->_new_img_name, 100)) {
         imagedestroy($thumb);
         throw new Exception('cannot save img_thumbs file');
     }
     imagedestroy($thumb);
     return $this;
 }
Esempio n. 5
0
 /**  
  * 输出验证码并把验证码的值保存的session中  
  */
 public static function entry()
 {
     // 图片宽(px)
     self::$imageL || (self::$imageL = self::$length * self::$fontSize * 1.5 + self::$fontSize * 1.5);
     // 图片高(px)
     self::$imageH || (self::$imageH = self::$fontSize * 2);
     // 建立一幅 self::$imageL x self::$imageH 的图像
     self::$_image = imagecreate(self::$imageL, self::$imageH);
     // 设置背景
     imagecolorallocate(self::$_image, self::$bg[0], self::$bg[1], self::$bg[2]);
     // 验证码字体随机颜色
     self::$_color = imagecolorallocate(self::$_image, mt_rand(1, 120), mt_rand(1, 120), mt_rand(1, 120));
     // 验证码使用随机字体,保证目录下有这些字体集
     $ttf = dirname(__FILE__) . '/ttfs/t' . mt_rand(1, 10) . '.ttf';
     if (self::$useNoise) {
         // 绘杂点
         self::_writeNoise();
     }
     if (self::$useCurve) {
         // 绘干扰线
         self::_writeCurve();
     }
     // 绘验证码
     $code = array();
     // 验证码
     $codeNX = 0;
     // 验证码第N个字符的左边距
     for ($i = 0; $i < self::$length; $i++) {
         $code[$i] = self::$codeSet[mt_rand(0, 28)];
         $codeNX += mt_rand(self::$fontSize * 1.2, self::$fontSize * 1.6);
         // 写一个验证码字符
         imagettftext(self::$_image, self::$fontSize, mt_rand(-40, 70), $codeNX, self::$fontSize * 1.5, self::$_color, $ttf, $code[$i]);
     }
     // 保存验证码
     isset($_SESSION) || session_start();
     $_SESSION[self::$seKey]['code'] = join('', $code);
     // 把验证码保存到session, 验证时注意是大写
     $_SESSION[self::$seKey]['time'] = time();
     // 验证码创建时间
     header('Pragma: no-cache');
     header("content-type: image/JPEG");
     // 输出图像
     imageJPEG(self::$_image);
     imagedestroy(self::$_image);
 }
Esempio n. 6
0
 function save($save)
 {
     /* change ImageCreateTrueColor to ImageCreate if your GD not supported ImageCreateTrueColor function*/
     $this->img["des"] = ImageCreateTrueColor($this->img["lebar_thumb"], $this->img["tinggi_thumb"]);
     @imagecopyresized($this->img["des"], $this->img["src"], 0, 0, 0, 0, $this->img["lebar_thumb"], $this->img["tinggi_thumb"], $this->img["lebar"], $this->img["tinggi"]);
     if ($this->img["format"] == "JPG" || $this->img["format"] == "JPEG") {
         //JPEG
         imageJPEG($this->img["des"], "{$save}", $this->img["quality"]);
     } elseif ($this->img["format"] == "PNG") {
         //PNG
         imagePNG($this->img["des"], "{$save}");
     } elseif ($this->img["format"] == "GIF") {
         //GIF
         imageGIF($this->img["des"], "{$save}");
     } elseif ($this->img["format"] == "WBMP") {
         //WBMP
         imageWBMP($this->img["des"], "{$save}");
     }
 }
Esempio n. 7
0
 private function createNewImage($newImg, $newName, $imgInfo)
 {
     switch ($imgInfo["type"]) {
         case 1:
             //gif
             $result = imageGif($newImg, $this->path . $newName);
             break;
         case 2:
             //jpg
             $result = imageJPEG($newImg, $this->path . $newName);
             break;
         case 3:
             //png
             $return = imagepng($newImg, $this->path . $newName);
             break;
     }
     imagedestroy($newImg);
     return $newName;
 }
Esempio n. 8
0
 function save($save = "", $gd_version)
 {
     if ($gd_version == 2) {
         $this->img["des"] = imagecreatetruecolor($this->img["lebar_thumb"], $this->img["tinggi_thumb"]);
         @imagecopyresampled($this->img["des"], $this->img["src"], 0, 0, 0, 0, $this->img["lebar_thumb"], $this->img["tinggi_thumb"], $this->img["lebar"], $this->img["tinggi"]);
     }
     if ($gd_version == 1) {
         $this->img["des"] = imagecreate($this->img["lebar_thumb"], $this->img["tinggi_thumb"]);
         @imagecopyresized($this->img["des"], $this->img["src"], 0, 0, 0, 0, $this->img["lebar_thumb"], $this->img["tinggi_thumb"], $this->img["lebar"], $this->img["tinggi"]);
     }
     if ($this->img["format"] == "JPG" || $this->img["format"] == "JPEG") {
         //JPEG
         imageJPEG($this->img["des"], "{$save}", $this->img["quality"]);
     } elseif ($this->img["format"] == "PNG") {
         //PNG
         imagePNG($this->img["des"], "{$save}");
     }
     // Memory cleanup
     @imageDestroy($this->img["des"]);
 }
Esempio n. 9
0
 public static function resize_bg($image, $model, $id, $width, $height)
 {
     $startImage = $image;
     $test_name = 'test-' . $width . '-' . $height . '-' . time() . '.jpg';
     if (!$image) {
         return '/images/blank.png';
     }
     $directory = self::checkAndCreateDirectory($model, $id, self::RESIZE_BG_PATH, $width, $height);
     $imageParts = explode('/', $image);
     $imageName = end($imageParts);
     try {
         $image_factory = Image::factory(PUBLIC_ROOT . 'files/' . $model . '/' . $id . '/' . $imageName);
     } catch (Exception $e) {
         return $startImage;
     }
     try {
         if (!file_exists($directory . $imageName)) {
             $img = imagecreate($width, $height);
             $white = ImageColorAllocate($img, 255, 255, 255);
             ImageFill($img, 0, 0, $white);
             header('Content-Type: image/jpg;');
             $test_file = APPPATH . 'cache/' . $test_name;
             imageJPEG($img, $test_file);
             $image = Image::factory($test_file);
             $image->watermark($image_factory->resize(intval($width), intval($height), Kohana_Image::AUTO))->save($directory . $imageName, 99);
             imageDestroy($img);
             @unlink($test_file);
         }
     } catch (Exception $e) {
         return $startImage;
     }
     $path = '/files/' . self::RESIZE_BG_PATH . '/' . $width;
     if ($height) {
         $path .= 'x' . $height;
     }
     if (file_exists($directory . $imageName)) {
         return $path . '/' . $model . '/' . $id . '/' . $imageName;
     }
     return $startImage;
 }
Esempio n. 10
0
 /**  
  * 输出验证码并把验证码的值保存的session中  
  */
 public static function entry()
 {
     // 图片宽(px)
     self::$imageL || (self::$imageL = self::$length * self::$fontSize * 1.5 + self::$fontSize * 1.5);
     // 图片高(px)
     self::$imageH || (self::$imageH = self::$fontSize * 2);
     // 建立一幅 self::$imageL x self::$imageH 的图像
     self::$_image = imagecreate(self::$imageL, self::$imageH);
     // 设置背景
     imagecolorallocate(self::$_image, self::$bg[0], self::$bg[1], self::$bg[2]);
     // 验证码字体随机颜色
     self::$_color = imagecolorallocate(self::$_image, mt_rand(1, 120), mt_rand(1, 120), mt_rand(1, 120));
     // 验证码使用随机字体,保证目录下有这些字体集
     $ttf = dirname(__FILE__) . '/ttfs/t' . mt_rand(1, 3) . '.ttf';
     if (self::$useNoise) {
         // 绘杂点
         self::_writeNoise();
     }
     if (self::$useCurve) {
         // 绘干扰线
         self::_writeCurve();
     }
     // 绘验证码
     $code = array();
     // 验证码
     $codeNX = 0;
     // 验证码第N个字符的左边距
     for ($i = 0; $i < self::$length; $i++) {
         $code[$i] = self::$codeSet[mt_rand(0, 28)];
         $codeNX += mt_rand(self::$fontSize * 1.2, self::$fontSize * 1.6);
         imagettftext(self::$_image, self::$fontSize, mt_rand(-40, 40), $codeNX, self::$fontSize * 1.5, self::$_color, $ttf, $code[$i]);
     }
     self::$code = join('', $code);
     // 输出图像
     imageJPEG(self::$_image);
     imagedestroy(self::$_image);
 }
Esempio n. 11
0
/**
* generates a constrained image and returns the data stream
* Good for making thumbnails or just constraining all  uploaded images.
*
* @param path       str: path to temp image (eg. '/home/user/web/temp')
* @param tmp_file   str: the original filename( eg. foo.jpg )
* @param constrain  str: x or y constrain (eg. 'x')
* @param size       int: constrained dimension size (eg. '200')
* @param value      arr: array containing the artist and album name for each loop
* @return           str: the JPEG filename from GD
*/
function generate_thumbnail($path, $tmp_file, $constrain, $size, $value)
{
    $rights = 0755;
    //get the source image size
    if ($imagesize = getimagesize($path . '/' . $tmp_file)) {
        //figure out the scaling ratio
        switch ($constrain) {
            case 'x':
                $ratio = $size / $imagesize[0];
                break;
            case 'y':
                $ratio = $size / $imagesize[1];
                break;
        }
        //read source format
        switch (substr($tmp_file, -3)) {
            case 'jpg':
                $source = imagecreatefromjpeg($path . '/' . $tmp_file);
                break;
            case 'gif':
                $source = imagecreatefromgif($path . '/' . $tmp_file);
                break;
            case 'png':
                $source = imagecreatefrompng($path . '/' . $tmp_file);
                break;
        }
        //open new resource file
        if ($source) {
            //resample the image using the ratio
            $th_xdim = (int) floor($ratio * $imagesize[0]);
            $th_ydim = (int) floor($ratio * $imagesize[1]);
            $tempdest = imagecreatetruecolor($th_xdim, $th_ydim);
            //make a copy of the thumbnail image in server memory
            imagecopyresampled($tempdest, $source, 0, 0, 0, 0, $th_xdim, $th_ydim, imagesx($source), imagesy($source));
            //we're done with the source, so we'll purge it
            imagedestroy($source);
            //copy the proper JPEG source to the server and chmod it to 644
            imageJPEG($tempdest, $path . '/' . $size . '-' . $tmp_file);
            chmod($path . '/' . $size . '-' . $tmp_file, $rights);
            //finally, clean up the rest of image memory
            imagedestroy($tempdest);
            //return the new filename for moving
            return $size . '-' . $tmp_file;
        } else {
            echo 'could not load source image into GD for:' . $value['artist_name'] . '/' . $value['album_name'];
        }
    } else {
        echo 'GD could not get the image dimensions for the media: ' . $value['artist_name'] . '/' . $value['album_name'];
    }
}
 /**
  * Appends information about the source image to the thumbnail.
  * 
  * @param	string		$thumbnail
  * @return	string
  */
 protected function appendSourceInfo($thumbnail)
 {
     if (!function_exists('imageCreateFromString') || !function_exists('imageCreateTrueColor')) {
         return $thumbnail;
     }
     $imageSrc = imageCreateFromString($thumbnail);
     // get image size
     $width = imageSX($imageSrc);
     $height = imageSY($imageSrc);
     // increase height
     $heightDst = $height + self::$sourceInfoLineHeight * 2;
     // create new image
     $imageDst = imageCreateTrueColor($width, $heightDst);
     imageAlphaBlending($imageDst, false);
     // set background color
     $background = imageColorAllocate($imageDst, 102, 102, 102);
     imageFill($imageDst, 0, 0, $background);
     // copy image
     imageCopy($imageDst, $imageSrc, 0, 0, 0, 0, $width, $height);
     imageSaveAlpha($imageDst, true);
     // get font size
     $font = 2;
     $fontWidth = imageFontWidth($font);
     $fontHeight = imageFontHeight($font);
     $fontColor = imageColorAllocate($imageDst, 255, 255, 255);
     // write source info
     $line1 = $this->sourceName;
     // imageString supports only ISO-8859-1 encoded strings
     if (CHARSET != 'ISO-8859-1') {
         $line1 = StringUtil::convertEncoding(CHARSET, 'ISO-8859-1', $line1);
     }
     // truncate text if necessary
     $maxChars = floor($width / $fontWidth);
     if (strlen($line1) > $maxChars) {
         $line1 = $this->truncateSourceName($line1, $maxChars);
     }
     $line2 = $this->sourceWidth . 'x' . $this->sourceHeight . ' ' . FileUtil::formatFilesize($this->sourceSize);
     // write line 1
     // calculate text position
     $textX = 0;
     $textY = 0;
     if ($fontHeight < self::$sourceInfoLineHeight) {
         $textY = intval(round((self::$sourceInfoLineHeight - $fontHeight) / 2));
     }
     if (strlen($line1) * $fontWidth < $width) {
         $textX = intval(round(($width - strlen($line1) * $fontWidth) / 2));
     }
     imageString($imageDst, $font, $textX, $height + $textY, $line1, $fontColor);
     // write line 2
     // calculate text position
     $textX = 0;
     $textY = 0;
     if ($fontHeight < self::$sourceInfoLineHeight) {
         $textY = self::$sourceInfoLineHeight + intval(round((self::$sourceInfoLineHeight - $fontHeight) / 2));
     }
     if (strlen($line2) * $fontWidth < $width) {
         $textX = intval(round(($width - strlen($line2) * $fontWidth) / 2));
     }
     imageString($imageDst, $font, $textX, $height + $textY, $line2, $fontColor);
     // output image
     ob_start();
     if ($this->imageType == 1 && function_exists('imageGIF')) {
         @imageGIF($imageDst);
         $this->mimeType = 'image/gif';
     } else {
         if (($this->imageType == 1 || $this->imageType == 3) && function_exists('imagePNG')) {
             @imagePNG($imageDst);
             $this->mimeType = 'image/png';
         } else {
             if (function_exists('imageJPEG')) {
                 @imageJPEG($imageDst, null, 90);
                 $this->mimeType = 'image/jpeg';
             } else {
                 return false;
             }
         }
     }
     @imageDestroy($imageDst);
     $thumbnail = ob_get_contents();
     ob_end_clean();
     return $thumbnail;
 }
Esempio n. 13
0
 /**
  * Write the image after being processed
  *
  * @param Asido_TMP &$tmp
  * @return boolean
  * @access protected
  */
 function __write(&$tmp)
 {
     // try to guess format from extension
     //
     if (!$tmp->save) {
         $p = pathinfo($tmp->target_filename);
         ($tmp->save = $this->__mime_metaphone[metaphone($p['extension'])]) || ($tmp->save = $this->__mime_soundex[soundex($p['extension'])]);
     }
     $result = false;
     switch ($tmp->save) {
         case 'image/gif':
             imageTrueColorToPalette($tmp->target, true, 256);
             $result = @imageGIF($tmp->target, $tmp->target_filename);
             break;
         case 'image/jpeg':
             $result = @imageJPEG($tmp->target, $tmp->target_filename, ASIDO_GD_JPEG_QUALITY);
             break;
         case 'image/wbmp':
             $result = @imageWBMP($tmp->target, $tmp->target_filename);
             break;
         default:
         case 'image/png':
             imageSaveAlpha($tmp->target, true);
             imageAlphaBlending($tmp->target, false);
             $result = @imagePNG($tmp->target, $tmp->target_filename);
             break;
     }
     @$this->__destroy_source($tmp);
     @$this->__destroy_target($tmp);
     return $result;
 }
Esempio n. 14
0
 function create_watermark($file)
 {
     //文件不存在则返回
     if (!file_exists($this->watermark_file) || !file_exists($file)) {
         return;
     }
     if (!function_exists('getImageSize')) {
         return;
     }
     //检查GD支持的文件类型
     $gd_allow_types = array();
     if (function_exists('ImageCreateFromGIF')) {
         $gd_allow_types['image/gif'] = 'ImageCreateFromGIF';
     }
     if (function_exists('ImageCreateFromPNG')) {
         $gd_allow_types['image/png'] = 'ImageCreateFromPNG';
     }
     if (function_exists('ImageCreateFromJPEG')) {
         $gd_allow_types['image/jpeg'] = 'ImageCreateFromJPEG';
     }
     //获取文件信息
     $fileinfo = getImageSize($file);
     $wminfo = getImageSize($this->watermark_file);
     if ($fileinfo[0] < $wminfo[0] || $fileinfo[1] < $wminfo[1]) {
         return;
     }
     if (array_key_exists($fileinfo['mime'], $gd_allow_types)) {
         if (array_key_exists($wminfo['mime'], $gd_allow_types)) {
             // 从文件创建图像
             $temp = $gd_allow_types[$fileinfo['mime']]($file);
             $temp_wm = $gd_allow_types[$wminfo['mime']]($this->watermark_file);
             // 水印位置
             switch ($this->watermark_pos) {
                 case 1:
                     //顶部居左
                     $dst_x = 0;
                     $dst_y = 0;
                     break;
                 case 2:
                     //顶部居中
                     $dst_x = ($fileinfo[0] - $wminfo[0]) / 2;
                     $dst_y = 0;
                     break;
                 case 3:
                     //顶部居右
                     $dst_x = $fileinfo[0];
                     $dst_y = 0;
                     break;
                 case 4:
                     //底部居左
                     $dst_x = 0;
                     $dst_y = $fileinfo[1];
                     break;
                 case 5:
                     //底部居中
                     $dst_x = ($fileinfo[0] - $wminfo[0]) / 2;
                     $dst_y = $fileinfo[1];
                     break;
                 case 6:
                     //底部居右
                     $dst_x = $fileinfo[0] - $wminfo[0];
                     $dst_y = $fileinfo[1] - $wminfo[1];
                     break;
                 default:
                     //随机
                     $dst_x = mt_rand(0, $fileinfo[0] - $wminfo[0]);
                     $dst_y = mt_rand(0, $fileinfo[1] - $wminfo[1]);
             }
             if (function_exists('ImageAlphaBlending')) {
                 ImageAlphaBlending($temp_wm, True);
             }
             // 设定图像的混色模式
             if (function_exists('ImageSaveAlpha')) {
                 ImageSaveAlpha($temp_wm, True);
             }
             // 保存完整的 alpha 通道信息
             //为图像添加水印
             if (function_exists('imageCopyMerge')) {
                 ImageCopyMerge($temp, $temp_wm, $dst_x, $dst_y, 0, 0, $wminfo[0], $wminfo[1], $this->watermark_trans);
             } else {
                 ImageCopyMerge($temp, $temp_wm, $dst_x, $dst_y, 0, 0, $wminfo[0], $wminfo[1]);
             }
             // 保存图片
             switch ($fileinfo['mime']) {
                 case 'image/jpeg':
                     @imageJPEG($temp, $file);
                     break;
                 case 'image/png':
                     @imagePNG($temp, $file);
                     break;
                 case 'image/gif':
                     @imageGIF($temp, $file);
                     break;
             }
             // 销毁零时图像
             @imageDestroy($temp);
             @imageDestroy($temp_wm);
         }
     }
 }
Esempio n. 15
0
function makewatermark($srcfile)
{
    global $_SCONFIG;
    if ($_SCONFIG['watermark'] && function_exists('imageCreateFromJPEG') && function_exists('imageCreateFromPNG') && function_exists('imageCopyMerge')) {
        $srcfile = A_DIR . '/' . $srcfile;
        $watermark_file = $_SCONFIG['watermarkfile'];
        $watermarkstatus = $_SCONFIG['watermarkstatus'];
        $fileext = fileext($watermark_file);
        $ispng = $fileext == 'png' ? true : false;
        $attachinfo = @getimagesize($srcfile);
        if (!empty($attachinfo) && is_array($attachinfo) && $attachinfo[2] != 1 && $attachinfo['mime'] != 'image/gif') {
        } else {
            return '';
        }
        $watermark_logo = $ispng ? @imageCreateFromPNG($watermark_file) : @imageCreateFromGIF($watermark_file);
        if (!$watermark_logo) {
            return '';
        }
        $logo_w = imageSX($watermark_logo);
        $logo_h = imageSY($watermark_logo);
        $img_w = $attachinfo[0];
        $img_h = $attachinfo[1];
        $wmwidth = $img_w - $logo_w;
        $wmheight = $img_h - $logo_h;
        if (is_readable($watermark_file) && $wmwidth > 100 && $wmheight > 100) {
            switch ($attachinfo['mime']) {
                case 'image/jpeg':
                    $dst_photo = imageCreateFromJPEG($srcfile);
                    break;
                case 'image/gif':
                    $dst_photo = imageCreateFromGIF($srcfile);
                    break;
                case 'image/png':
                    $dst_photo = imageCreateFromPNG($srcfile);
                    break;
                default:
                    break;
            }
            switch ($watermarkstatus) {
                case 1:
                    $x = +5;
                    $y = +5;
                    break;
                case 2:
                    $x = ($img_w - $logo_w) / 2;
                    $y = +5;
                    break;
                case 3:
                    $x = $img_w - $logo_w - 5;
                    $y = +5;
                    break;
                case 4:
                    $x = +5;
                    $y = ($img_h - $logo_h) / 2;
                    break;
                case 5:
                    $x = ($img_w - $logo_w) / 2;
                    $y = ($img_h - $logo_h) / 2;
                    break;
                case 6:
                    $x = $img_w - $logo_w - 5;
                    $y = ($img_h - $logo_h) / 2;
                    break;
                case 7:
                    $x = +5;
                    $y = $img_h - $logo_h - 5;
                    break;
                case 8:
                    $x = ($img_w - $logo_w) / 2;
                    $y = $img_h - $logo_h - 5;
                    break;
                case 9:
                    $x = $img_w - $logo_w - 5;
                    $y = $img_h - $logo_h - 5;
                    break;
            }
            if ($ispng) {
                $watermark_photo = imagecreatetruecolor($img_w, $img_h);
                imageCopy($watermark_photo, $dst_photo, 0, 0, 0, 0, $img_w, $img_h);
                imageCopy($watermark_photo, $watermark_logo, $x, $y, 0, 0, $logo_w, $logo_h);
                $dst_photo = $watermark_photo;
            } else {
                imageAlphaBlending($watermark_logo, true);
                imageCopyMerge($dst_photo, $watermark_logo, $x, $y, 0, 0, $logo_w, $logo_h, $_SCONFIG['watermarktrans']);
            }
            switch ($attachinfo['mime']) {
                case 'image/jpeg':
                    imageJPEG($dst_photo, $srcfile, $_SCONFIG['watermarkjpgquality']);
                    break;
                case 'image/gif':
                    imageGIF($dst_photo, $srcfile);
                    break;
                case 'image/png':
                    imagePNG($dst_photo, $srcfile);
                    break;
            }
        }
    }
}
 function convertImage($type)
 {
     /* check the converted image type availability,
        if it is not available, it will be casted to jpeg :) */
     $validtype = $this->validateType($type);
     if ($this->output) {
         /* show the image  */
         switch ($validtype) {
             case 'jpeg':
             case 'jpg':
                 header("Content-type: image/jpeg");
                 if ($this->imtype == 'gif' or $this->imtype == 'png') {
                     $image = $this->replaceTransparentWhite($this->im);
                     imageJPEG($image);
                 } else {
                     imageJPEG($this->im);
                 }
                 break;
             case 'gif':
                 header("Content-type: image/gif");
                 imageGIF($this->im);
                 break;
             case 'png':
                 header("Content-type: image/png");
                 imagePNG($this->im);
                 break;
             case 'wbmp':
                 header("Content-type: image/vnd.wap.wbmp");
                 imageWBMP($this->im);
                 break;
             case 'swf':
                 header("Content-type: application/x-shockwave-flash");
                 $this->imageSWF($this->im);
                 break;
         }
         // Memory cleanup
         @imagedestroy($this->im);
     } else {
         /* save the image  */
         switch ($validtype) {
             case 'jpeg':
             case 'jpg':
                 if ($this->imtype == 'gif' or $this->imtype == 'png') {
                     /* replace transparent with white */
                     $image = $this->replaceTransparentWhite($this->im);
                     imageJPEG($image, $this->finalFilePath . $this->imname . ".jpg");
                 } else {
                     imageJPEG($this->im, $this->finalFilePath . $this->imname . ".jpg");
                 }
                 break;
             case 'gif':
                 imageGIF($this->im, $this->finalFilePath . $this->imname . ".gif");
                 break;
             case 'png':
                 imagePNG($this->im, $this->finalFilePath . $this->imname . ".png");
                 break;
             case 'wbmp':
                 imageWBMP($this->im, $this->finalFilePath . $this->imname . ".wbmp");
                 break;
             case 'swf':
                 $this->imageSWF($this->im, $this->finalFilePath . $this->imname . ".swf");
                 break;
         }
         // Memory cleanup
         @imagedestroy($this->im);
     }
 }
Esempio n. 17
0
 function watermark($target, $watermark_file, $ext, $watermarkstatus = 9, $watermarktrans = 50)
 {
     $gdsurporttype = array();
     if (function_exists('imageAlphaBlending') && function_exists('getimagesize')) {
         if (function_exists('imageGIF')) {
             $gdsurporttype[] = 'gif';
         }
         if (function_exists('imagePNG')) {
             $gdsurporttype[] = 'png';
         }
         if (function_exists('imageJPEG')) {
             $gdsurporttype[] = 'jpg';
             $gdsurporttype[] = 'jpeg';
         }
     }
     if ($gdsurporttype && in_array($ext, $gdsurporttype)) {
         $attachinfo = getimagesize($target);
         $watermark_logo = imageCreateFromGIF($watermark_file);
         $logo_w = imageSX($watermark_logo);
         $logo_h = imageSY($watermark_logo);
         $img_w = $attachinfo[0];
         $img_h = $attachinfo[1];
         $wmwidth = $img_w - $logo_w;
         $wmheight = $img_h - $logo_h;
         $animatedgif = 0;
         if ($attachinfo['mime'] == 'image/gif') {
             $fp = fopen($target, 'rb');
             $targetcontent = fread($fp, 9999999);
             fclose($fp);
             $animatedgif = strpos($targetcontent, 'NETSCAPE2.0') === FALSE ? 0 : 1;
         }
         if ($watermark_logo && $wmwidth > 10 && $wmheight > 10 && !$animatedgif) {
             switch ($attachinfo['mime']) {
                 case 'image/jpeg':
                     $dst_photo = imageCreateFromJPEG($target);
                     break;
                 case 'image/gif':
                     $dst_photo = imageCreateFromGIF($target);
                     break;
                 case 'image/png':
                     $dst_photo = imageCreateFromPNG($target);
                     break;
             }
             switch ($watermarkstatus) {
                 case 1:
                     $x = +5;
                     $y = +5;
                     break;
                 case 2:
                     $x = ($logo_w + $img_w) / 2;
                     $y = +5;
                     break;
                 case 3:
                     $x = $img_w - $logo_w - 5;
                     $y = +5;
                     break;
                 case 4:
                     $x = +5;
                     $y = ($logo_h + $img_h) / 2;
                     break;
                 case 5:
                     $x = ($logo_w + $img_w) / 2;
                     $y = ($logo_h + $img_h) / 2;
                     break;
                 case 6:
                     $x = $img_w - $logo_w;
                     $y = ($logo_h + $img_h) / 2;
                     break;
                 case 7:
                     $x = +5;
                     $y = $img_h - $logo_h - 5;
                     break;
                 case 8:
                     $x = ($logo_w + $img_w) / 2;
                     $y = $img_h - $logo_h;
                     break;
                 case 9:
                     $x = $img_w - $logo_w - 5;
                     $y = $img_h - $logo_h - 5;
                     break;
             }
             imageAlphaBlending($watermark_logo, FALSE);
             imagesavealpha($watermark_logo, TRUE);
             imageCopyMerge($dst_photo, $watermark_logo, $x, $y, 0, 0, $logo_w, $logo_h, $watermarktrans);
             switch ($attachinfo['mime']) {
                 case 'image/jpeg':
                     imageJPEG($dst_photo, $target);
                     break;
                 case 'image/gif':
                     imageGIF($dst_photo, $target);
                     break;
                 case 'image/png':
                     imagePNG($dst_photo, $target);
                     break;
             }
         }
     }
 }
 function convertImage($type)
 {
     /* check the converted image type availability,
        if it is not available, it will be casted to jpeg :) */
     $validtype = $this->validateType($type);
     if ($this->output) {
         /* show the image  */
         switch ($validtype) {
             case 'jpeg':
                 // Added jpe
             // Added jpe
             case 'jpe':
             case 'jpg':
                 header("Content-type: image/jpeg");
                 if ($this->imtype == 'gif' or $this->imtype == 'png') {
                     $image = $this->replaceTransparentWhite($this->im);
                     @imageJPEG($image);
                 } else {
                     @imageJPEG($this->im);
                 }
                 break;
             case 'gif':
                 header("Content-type: image/gif");
                 @imageGIF($this->im);
                 break;
             case 'png':
                 header("Content-type: image/png");
                 @imagePNG($this->im);
                 break;
             case 'wbmp':
                 header("Content-type: image/vnd.wap.wbmp");
                 @imageWBMP($this->im);
                 break;
             case 'swf':
                 header("Content-type: application/x-shockwave-flash");
                 $this->imageSWF($this->im);
                 break;
         }
     } else {
         // Added Support vor different directory
         if (DEFINED('V_TEMP_DIR')) {
             $this->newimname = V_TEMP_DIR . $this->imname . '.' . $validtype;
         } else {
             $this->newimname = $this->imname . '.' . $validtype;
         }
         /* save the image  */
         switch ($validtype) {
             case 'jpeg':
                 // Added jpe
             // Added jpe
             case 'jpe':
             case 'jpg':
                 if ($this->imtype == 'gif' or $this->imtype == 'png') {
                     /* replace transparent with white */
                     $image = $this->replaceTransparentWhite($this->im);
                     @imageJPEG($image, $this->newimname);
                 } else {
                     @imageJPEG($this->im, $this->newimname);
                 }
                 break;
             case 'gif':
                 @imageGIF($this->im, $this->newimname);
                 break;
             case 'png':
                 @imagePNG($this->im, $this->newimname);
                 break;
             case 'wbmp':
                 @imageWBMP($this->im, $this->newimname);
                 break;
             case 'swf':
                 $this->imageSWF($this->im, $this->newimname);
                 break;
         }
     }
 }
Esempio n. 19
0
 /**
  * this function uses the gdimage library to resize an image and save it to a path 
  * or replace the existing file.
  * 
  * @param  string  $cInput   [file path for the source image]
  * @param  string  $cOutput  [the output path]
  * @param  integer $nH       [the image height]
  * @param  integer $nW       [the image width]
  * @param  string  $xType    [alternate ways to crop image]
  * @param  integer $nQuality [image quality]
  * 
  */
 public function resizeImage($cInput, $cOutput, $nH = 1600, $nW = 2560, $xType = 'normal', $nQuality = 100)
 {
     if (function_exists('imagecreatefromgif')) {
         $src_img = '';
         $nH == $nW ? $xType = 'square' : false;
         $cOutput == null ? $cOutput = $cInput : false;
         $cType = strtolower(substr(stripslashes($cInput), strrpos(stripslashes($cInput), '.')));
         if ($cType == '.gif' || $cType == 'image/gif') {
             $src_img = imagecreatefromgif($cInput);
             /* Attempt to open */
             $cType = 'image/gif';
         } elseif ($cType == '.png' || $cType == 'image/png' || $cType == 'image/x-png') {
             $src_img = imagecreatefrompng($cInput);
             /* Attempt to open */
             $cType = 'image/x-png';
         } elseif ($cType == '.bmp' || $cType == 'image/bmp') {
             $src_img = imagecreatefrombmp($cInput);
             /* Attempt to open */
             $cType = 'image/bmp';
         } elseif ($cType == '.jpg' || $cType == '.jpeg' || $cType == 'image/jpg' || $cType == 'image/jpeg' || $cType == 'image/pjpeg') {
             $src_img = imagecreatefromjpeg($cInput);
             /* Attempt to open */
             $cType = 'image/jpeg';
         } else {
         }
         if (!$src_img) {
             $src_img = imagecreatefromgif(FOONSTER_PATH . '/images/widget.gif');
             /* Attempt to open */
             $cType = 'image/gif';
         } else {
             $tmp_img;
             list($width, $height) = getimagesize($cInput);
             if ($xType == 'square' && $width != $height) {
                 $biggestSide = '';
                 $cropPercent = 0.5;
                 $cropWidth = 0;
                 $cropHeight = 0;
                 $c1 = array();
                 if ($width > $height) {
                     $biggestSide = $width;
                     $cropWidth = round($biggestSide * $cropPercent);
                     $cropHeight = round($biggestSide * $cropPercent);
                     $c1 = array("x" => ($width - $cropWidth) / 2, "y" => ($height - $cropHeight) / 2);
                 } else {
                     $biggestSide = $height;
                     $cropWidth = round($biggestSide * $cropPercent);
                     $cropHeight = round($biggestSide * $cropPercent);
                     $c1 = array("x" => ($width - $cropWidth) / 2, "y" => ($height - $cropHeight) / 7);
                 }
                 $thumbSize = $nH;
                 if ($cType == 'image/gif') {
                     $tmp_img = imagecreate($thumbSize, $thumbSize);
                     imagecolortransparent($tmp_img, imagecolorallocate($tmp_img, 0, 0, 0));
                     imagecopyresized($tmp_img, $src_img, 0, 0, $c1['x'], $c1['y'], $thumbSize, $thumbSize, $cropWidth, $cropHeight);
                 } elseif ($cType == 'image/x-png') {
                     $tmp_img = imagecreatetruecolor($thumbSize, $thumbSize);
                     imagecopyresampled($tmp_img, $src_img, 0, 0, $c1['x'], $c1['y'], $thumbSize, $thumbSize, $cropWidth, $cropHeight);
                 } elseif ($cType == 'image/bmp') {
                     $tmp_img = imagecreatetruecolor($thumbSize, $thumbSize);
                     imagecopyresampled($tmp_img, $src_img, 0, 0, $c1['x'], $c1['y'], $thumbSize, $thumbSize, $cropWidth, $cropHeight);
                 } elseif ($cType == 'image/jpeg') {
                     $tmp_img = imagecreatetruecolor($thumbSize, $thumbSize);
                     imagecopyresampled($tmp_img, $src_img, 0, 0, $c1['x'], $c1['y'], $thumbSize, $thumbSize, $cropWidth, $cropHeight);
                 } else {
                     $tmp_img = imagecreatetruecolor($thumbSize, $thumbSize);
                     imagecopyresampled($tmp_img, $src_img, 0, 0, $c1['x'], $c1['y'], $thumbSize, $thumbSize, $cropWidth, $cropHeight);
                 }
                 imagedestroy($src_img);
                 $src_img = $tmp_img;
             } else {
                 $ow = imagesx($src_img);
                 $oh = imagesy($src_img);
                 if ($nH == 0 && $nW == 0) {
                     $nH = $oh;
                     $nW = $ow;
                 }
                 if ($nH == 0) {
                     $nH = $nW;
                 }
                 if ($nW == 0) {
                     $nW = $nH;
                 }
                 if ($nH > $oh && $nW > $ow) {
                     $width = $ow;
                     $height = $oh;
                 } else {
                     if ($nW && $ow < $oh) {
                         $nW = $nH / $oh * $ow;
                     } else {
                         $nH = $nW / $ow * $oh;
                     }
                     $width = $nW;
                     $height = $nH;
                 }
                 if ($cType == 'image/gif') {
                     $tmp_img = imagecreate($width, $height);
                     imagecolortransparent($tmp_img, imagecolorallocate($tmp_img, 0, 0, 0));
                     imagecopyresized($tmp_img, $src_img, 0, 0, $off_w, $off_h, $width, $height, $ow, $oh);
                 } elseif ($cType == 'image/x-png') {
                     $tmp_img = imagecreatetruecolor($width, $height);
                     imagecopyresampled($tmp_img, $src_img, 0, 0, $off_w, $off_h, $width, $height, $ow, $oh);
                 } elseif ($cType == 'image/bmp') {
                     $tmp_img = imagecreatetruecolor($width, $height);
                     imagecopyresampled($tmp_img, $src_img, 0, 0, $off_w, $off_h, $width, $height, $ow, $oh);
                 } elseif ($cType == 'image/jpeg') {
                     $tmp_img = imagecreatetruecolor($width, $height);
                     imagecopyresampled($tmp_img, $src_img, 0, 0, $off_w, $off_h, $width, $height, $ow, $oh);
                 } else {
                     $tmp_img = imagecreatetruecolor($width, $height);
                     imagecopyresampled($tmp_img, $src_img, 0, 0, $off_w, $off_h, $width, $height, $ow, $oh);
                 }
                 imagedestroy($src_img);
                 $src_img = $tmp_img;
             }
         }
         // set the output
         if ($cType == 'image/gif') {
             imageGIF($src_img, $cOutput);
         } elseif ($cType == 'image/x-png') {
             imagePNG($src_img, $cOutput);
         } elseif ($cType == 'image/bmp') {
             imageJPEG($src_img, $cOutput, $nQuality);
         } elseif ($cType == 'image/jpeg') {
             imageJPEG($src_img, $cOutput, $nQuality);
         } else {
             imageJPEG($src_img, $cOutput, $nQuality);
         }
     }
 }
Esempio n. 20
0
 /**
  * Prints out and cache the thumbnail. Returns verbose errors.
  * 
  * @access public
  * @param string $image The Relative Path to the image
  * @param integer $width The Width of the new thumbnail
  * @param integer $height The Height of the thumbnail
  * @param boolean $return_img Set to true to return the string instead of outputting it. Default to false
  * @param boolean $display_inline If set to true, heaers sent to browser will instruct it to display the image inline instead of asking the user to download. Defaults to true.
  * @return string
  * 
  */
 function print_thumbnail($image, $width, $height, $return_img = false, $display_inline = true, $target_file = false)
 {
     //Check parameters
     if (empty($image) || empty($width) || empty($height)) {
         return $this->set_error("Method print_thumbnail: Missing Parameters");
     }
     if (isset($this->currentRealFile) && is_file($this->currentRealFile)) {
         $image = $this->currentRealFile;
     }
     //Check whether $image is a remote address
     if ($this->is_remote($image) == 1) {
         $is_remote = true;
         //Check that file exists (Check only enabled in PHP 5 because only PHP 5 supports for checking remote files
         if (phpversion() >= 5) {
             if (!file_exists($image)) {
                 return $this->set_error("Method print_thumbnail: Error. The file '{$image}' you specified does not exists or cannot be accessed.");
             }
         }
         $image_data = $this->retrieve_remote_file($image, true, false, 1);
     } elseif ($this->is_remote($image) == 0) {
         $is_remote = false;
         if (!file_exists($image)) {
             return $this->set_error("Method print_thumbnail: Error. The file '{$image}' you specified does not exists or cannot be accessed.");
         }
         $image_data = implode("", file($image));
     }
     if (!is_string($image_data)) {
         return $this->set_error("Method print_thumbnail: Error, could not read image file '{$image}'.");
     }
     $array = $this->retrieve_image_data($image);
     if (!$array) {
         return $this->set_error("Method print_thumbnail: Unable to determine Image '{$image}' type and/or dimensions.");
     }
     list($ori_width, $ori_height, $format) = $array;
     //Check whether format is supported
     if (!array_key_exists($format, $this->file_ext)) {
         return $this->set_error("Method print_thumbnail: Image '{$image}' format is not supported.");
     }
     //Check that cache is enabled, cache DIR is writable, cache DIR exists
     if ($this->is_cacheable()) {
         //Passed eh? Generate the root dir of request file
         if ($is_remote != true) {
             $transformed = realpath($image);
             $hash = sha1_file($image);
         } else {
             $transformed = $image;
             $hash = sha1($image_data);
         }
         //Check if a version exists
         if ($this->exif_rotation) {
             $cache_file = $this->cache_dir . sha1($transformed) . "." . $width . "." . $height . ".rotated." . $hash . "." . $this->file_ext[$format];
         } else {
             $cache_file = $this->cache_dir . sha1($transformed) . "." . $width . "." . $height . "." . $hash . "." . $this->file_ext[$format];
         }
         if (file_exists($cache_file)) {
             if ($return_img == false) {
                 //AJXP_Logger::debug("Using Cache");
                 //die($cache_file);
                 header("Expires: " . gmdate("D, d M Y H:i:s") . " GMT");
                 header("Cache-Control: no-store, no-cache, must-revalidate");
                 header("Pragma: no-cache");
                 header("Content-Transfer-Encoding: binary");
                 header("Content-type: " . image_type_to_mime_type($format));
                 if ($display_inline == true) {
                     header("Content-Disposition: inline; filename=\"" . time() . "." . $this->file_ext[$format] . "\"");
                 } else {
                     header("Content-Disposition: attachment; filename=\"" . time() . "." . $this->file_ext[$format] . "\"");
                 }
                 print implode("", file($cache_file));
                 die;
                 //Prepare redirectional URL
                 $redir_url = $_SERVER["HTTP_HOST"] . dirname($_SERVER["PHP_SELF"]) . "/" . $cache_file;
                 //Remove instances of double slashes "//"
                 $redir_url = str_replace("//", "/", $redir_url);
                 header("Location: http://{$redir_url}");
                 die;
             } else {
                 return implode("", file($cache_file));
             }
         } else {
             $handle = @opendir($this->cache_dir);
             if ($handle !== FALSE) {
                 while (false !== ($file = readdir($handle))) {
                     if ($this->exif_rotation) {
                         $rotated = "\\.rotated";
                     } else {
                         $rotated = "";
                     }
                     if (preg_match("/^" . preg_quote(sha1($transformed)) . "\\.[0-9]+\\.[0-9]+" . $rotated . "\\.([0-9a-z]{40})\\.(.+?)\$/i", $file, $matches)) {
                         //Hash is in [1]
                         //Check to see if the file data is the same. If it is, then don't delete it.
                         if ($matches[1] != $hash) {
                             $matched[] = $file;
                         }
                     }
                 }
                 closedir($handle);
                 if (!empty($matched)) {
                     for ($i = 0; $i <= count($matched) - 1; $i++) {
                         @unlink($this->cache_dir . $matched[$i]);
                     }
                 }
             }
         }
     }
     $gd_info = gd_info();
     //Special GIF handling
     if ($format == 1 && $gd_info["GIF Create Support"] != true) {
         //return $this -> set_error("Method print_thumbnail: Error, GIF support is unavaliable for PHP Version ".phpversion());
         //Image Outputted will be in PNG Format
         $format = 3;
     }
     $handle = @imagecreatefromstring($image_data);
     if ($handle == false) {
         return $this->set_error("Method print_thumbnail: Unsupported Image '{$image}' type");
     }
     //Exif Orientation patch
     $orientation = $this->exiforientation($image, true);
     if ($this->rotationsupported($orientation) and $orientation > 4) {
         $width2 = $width;
         $width = $height;
         $height = $width2;
     }
     //Now lets resize it
     //First lets create a new image handler which will be the thumbnailed image
     $thumbnail = imagecreatetruecolor($width, $height);
     if (!$thumbnail) {
         return $this->set_error("Method print_thumbnail: A thumbnail image '{$image}' could not be created");
     }
     /*  Image Format Special Handlinng */
     //GIF truecolour to palette - preserve transparency
     if ($format == 1) {
         imagetruecolortopalette($handle, true, 256);
     }
     //PNG Alpha Channel saving
     if ($format == 3) {
         //Set to save alpha channel info in source and destination
         imagealphablending($handle, false);
         imagesavealpha($handle, true);
         imagealphablending($thumbnail, false);
         imagesavealpha($thumbnail, true);
     }
     //Resize it
     if (!$this->fastimagecopyresampled($thumbnail, $handle, 0, 0, 0, 0, $width, $height, ImageSX($handle), ImageSY($handle), $this->thumb_quality)) {
         return $this->set_error("Method print_thumbnail: Failed resizing image '{$image}'.");
     }
     // Rotate if JPEG and Exif Information is available
     $orientation = $this->exiforientation($image, true);
     if ($this->rotationsupported($orientation)) {
         switch ($orientation) {
             case 2:
                 // mirror horizontal
                 @imageflip($thumbnail, IMG_FLIP_HORIZONTAL);
                 break;
             case 3:
                 // rotate 180
                 $thumbnail = @imagerotate($thumbnail, 180, imagecolorallocate($thumbnail, 255, 255, 255));
                 break;
             case 4:
                 // mirror vertical
                 @imageflip($thumbnail, IMG_FLIP_VERTICAL);
                 break;
             case 5:
                 // mirror horizontal, 90 rotate left
                 @imageflip($thumbnail, IMG_FLIP_HORIZONTAL);
                 $thumbnail = @imagerotate($thumbnail, 90, imagecolorallocate($thumbnail, 255, 255, 255));
                 break;
             case 6:
                 // 90 rotate right
                 $thumbnail = @imagerotate($thumbnail, -90, imagecolorallocate($thumbnail, 255, 255, 255));
                 break;
             case 7:
                 // mirror horizontal, 90 rotate right
                 @imageflip($thumbnail, IMG_FLIP_HORIZONTAL);
                 $thumbnail = @imagerotate($thumbnail, -90, imagecolorallocate($thumbnail, 255, 255, 255));
                 break;
             case 8:
                 // 90 rotate left
                 $thumbnail = @imagerotate($thumbnail, 90, imagecolorallocate($thumbnail, 255, 255, 255));
                 break;
         }
     }
     //Cache it
     if ($this->is_cacheable()) {
         switch ($format) {
             case 1:
                 $cached = @imagegif($thumbnail, $cache_file);
                 break;
             case 2:
                 $cached = @imageJPEG($thumbnail, $cache_file, 100);
                 break;
             case 3:
                 $cached = @imagepng($thumbnail, $cache_file);
                 break;
             case 15:
                 $cached = @imagewbmp($thumbnail, $cache_file);
                 break;
             case 16:
                 $cached = @imagexbm($thumbnail, $cache_file);
                 break;
             default:
                 $cached = false;
         }
         if (!$cached) {
             return $this->set_error("Method print_thumbnail 1: Error in cache generation of image '{$image}'.");
         }
     }
     if ($target_file != false) {
         $wrappers = stream_get_wrappers();
         $wrappers_re = '(' . implode('|', $wrappers) . ')';
         $isStream = preg_match("!^{$wrappers_re}://!", $target_file) === 1;
         if ($isStream) {
             $backToStreamTarget = $target_file;
             $target_file = tempnam(AJXP_Utils::getAjxpTmpDir(), "pthumb_");
         }
         switch ($format) {
             case 1:
                 $cached = @imagegif($thumbnail, $target_file);
                 break;
             case 2:
                 $cached = @imageJPEG($thumbnail, $target_file, 100);
                 break;
             case 3:
                 $cached = @imagepng($thumbnail, $target_file);
                 break;
             case 15:
                 $cached = @imagewbmp($thumbnail, $target_file);
                 break;
             case 16:
                 $cached = @imagexbm($thumbnail, $target_file);
                 break;
             default:
                 $cached = false;
         }
         if ($cached && $isStream) {
             $cached = @copy($target_file, $backToStreamTarget);
             @unlink($target_file);
         }
         if (!$cached) {
             return $this->set_error("Method print_thumbnail: Error in cache generation of image '{$image}'.");
         }
         return true;
     }
     if ($return_img == false) {
         header("Expires: " . gmdate("D, d M Y H:i:s") . " GMT");
         header("Cache-Control: no-store, no-cache, must-revalidate");
         header("Pragma: no-cache");
         header("Content-Transfer-Encoding: binary");
         header("Content-type: " . image_type_to_mime_type($format));
         if ($display_inline == true) {
             header("Content-Disposition: inline; filename=\"" . time() . "." . $this->file_ext[$format] . "\"");
         } else {
             header("Content-Disposition: attachment; filename=\"" . time() . "." . $this->file_ext[$format] . "\"");
         }
         if ($this->is_cacheable()) {
             echo implode("", file($cache_file));
         } else {
             switch ($format) {
                 case 1:
                     $outputed = @imagegif($thumbnail);
                     break;
                 case 2:
                     $outputed = @imageJPEG($thumbnail, null, 100);
                     break;
                 case 3:
                     $outputed = @imagepng($thumbnail);
                     break;
                 case 15:
                     $outpupted = @imagewbmp($thumbnail);
                     break;
                 case 16:
                     $outputed = @imagexbm($thumbnail, NULL);
                     break;
                 default:
                     $outputed = false;
             }
             if (!$outputed) {
                 return $this->set_error("Method print_thumbnail: Error outputting Image '{$image}'");
             }
         }
     } else {
         if ($this->is_cacheable()) {
             return implode("", file($cache_file));
         } else {
             return $this->set_error("Method print_thumbnail: Cannot return image '{$image}'! Cache must be enabled!");
         }
     }
     //Destroy the image
     imagedestroy($handle);
     imagedestroy($thumbnail);
     //Clear any cache; if needed
     $this->clear_cache();
 }
Esempio n. 21
0
 /**
  * function imageCreate (resource $thumb)
  *
  * Create a new image from the $thumb resource
  *
  * return booelan
  */
 function imageCreate($thumb)
 {
     if ($this->data[2] == 1) {
         $ok = imageGIF($thumb, $this->target, $this->quality);
     } elseif ($this->data[2] == 3) {
         $quality = 10 - round($this->quality / 10);
         $quality = $quality < 0 ? 0 : ($quality > 9 ? 9 : $quality);
         $ok = imagePNG($thumb, $this->target, $quality);
     } else {
         $ok = imageJPEG($thumb, $this->target, $this->quality);
     }
     if ($ok) {
         imageDestroy($thumb);
         return true;
     } else {
         return false;
     }
 }
Esempio n. 22
0
 public static function thumbComplete($o_file, $fileName, $t_ht = 100, $x, $y, $width, $height, $ow, $sizes = array())
 {
     $image_info = getImageSize($o_file);
     // see EXIF for faster way
     switch ($image_info['mime']) {
         case 'image/gif':
             if (imagetypes() & IMG_GIF) {
                 // not the same as IMAGETYPE
                 $o_im = imageCreateFromGIF($o_file);
             }
             break;
         case 'image/jpeg':
             if (imagetypes() & IMG_JPG) {
                 $o_im = imageCreateFromJPEG($o_file);
             }
             break;
         case 'image/png':
             if (imagetypes() & IMG_PNG) {
                 $o_im = imageCreateFromPNG($o_file);
             }
             break;
         case 'image/wbmp':
             if (imagetypes() & IMG_WBMP) {
                 $o_im = imageCreateFromWBMP($o_file);
             }
             break;
         default:
             break;
     }
     $o_wd = imagesx($o_im);
     $o_ht = imagesy($o_im);
     $size = $o_wd / $ow;
     echo $size . '<br>';
     echo $x * $size . '<br>';
     echo $y * $size . '<br>';
     echo $sizes['width'] . '<br>';
     echo $sizes['height'] . '<br>';
     echo $width * $size . '<br>';
     echo $height * $size . '<br>';
     //        die;
     $new_im = imageCreateTrueColor($width, $height);
     if (empty($sizes)) {
         imagecopyresampled($new_im, $o_im, 0, 0, $x * $size, $y * $size, $width * $size, $height * $size, $width * $size, $height * $size);
     } else {
         imagecopyresampled($new_im, $o_im, 0, 0, $x * $size, $y * $size, $sizes['width'], $sizes['height'], $width * $size, $height * $size);
     }
     imageJPEG($new_im, $fileName, 100);
     chmod($fileName, 0777);
     imageDestroy($o_im);
     imageDestroy($new_im);
     return true;
 }
     header("Content-type: image/jpeg");
     header("Cache-control: no-cache");
     $image = ImageCreateFromJPEG($orgimg);
     $orgX = ImageSX($image);
     $orgY = ImageSY($image);
     if ($orgX < $ImageResizeX) {
         $newX = $orgX;
         $newY = $orgY;
     } else {
         $newX = $ImageResizeX;
         $newY = $orgY / $orgX * $ImageResizeX;
     }
     $newimage = ImageCreateTrueColor($newX, $newY);
     ImageCopyResized($newimage, $image, 0, 0, 0, 0, $newX, $newY, $orgX, $orgY);
     imagedestroy($image);
     imageJPEG($newimage);
     imagedestroy($newimage);
 } else {
     if (eregi('.gif', $orgimg) || $imginfo[2] == IMAGETYPE_GIF) {
         //GIFファイルは無理やりjpegに変換して表示します。
         header("Content-type: image/jpeg");
         header("Cache-control: no-cache");
         $image = ImageCreateFromGIF($orgimg);
         $orgX = ImageSX($image);
         $orgY = ImageSY($image);
         if ($orgX < $ImageResizeX) {
             $newX = $orgX;
             $newY = $orgY;
         } else {
             $newX = $ImageResizeX;
             $newY = $orgY / $orgX * $ImageResizeX;
Esempio n. 24
0
 /**
  * Prints out and cache the thumbnail. Returns verbose errors.
  * 
  * @access public
  * @param string $image The Relative Path to the image
  * @param integer $width The Width of the new thumbnail
  * @param integer $height The Height of the thumbnail
  * @param boolean $return_img Set to true to return the string instead of outputting it. Default to false
  * @param boolean $display_inline If set to true, heaers sent to browser will instruct it to display the image inline instead of asking the user to download. Defaults to true.
  * @return string
  * 
  */
 function print_thumbnail($image, $width, $height, $return_img = false, $display_inline = true)
 {
     //Check parameters
     if (empty($image) || empty($width) || empty($height)) {
         return $this->set_error("Method print_thumbnail: Missing Parameters");
     }
     //Check whether $image is a remote address
     if ($this->is_remote($image) == 1) {
         $is_remote = true;
         //Check that file exists (Check only enabled in PHP 5 because only PHP 5 supports for checking remote files
         if (phpversion() >= 5) {
             if (!file_exists($image)) {
                 return $this->set_error("Method print_thumbnail: Error. The file '{$image}' you specified does not exists or cannot be accessed.");
             }
         }
         $image_data = $this->retrieve_remote_file($image, true, false, 1);
     } elseif ($this->is_remote($image) == 0) {
         $is_remote = false;
         if (!file_exists($image)) {
             return $this->set_error("Method print_thumbnail: Error. The file '{$image}' you specified does not exists or cannot be accessed.");
         }
         $image_data = @join(file($image));
     }
     if (!is_string($image_data)) {
         return $this->set_error("Method print_thumbnail: Error, could not read image file '{$image}'.");
     }
     $array = $this->retrieve_image_data($image);
     if (!$array) {
         return $this->set_error("Method print_thumbnail: Unable to determine Image '{$image}' type and/or dimensions.");
     }
     list($ori_width, $ori_height, $format) = $array;
     //Check whether format is supported
     if (!array_key_exists($format, $this->file_ext)) {
         return $this->set_error("Method print_thumbnail: Image '{$image}' format is not supported.");
     }
     //Check that cache is enabled, cache DIR is writable, cache DIR exists
     if ($this->is_cacheable()) {
         //Passed eh? Generate the root dir of request file
         if ($is_remote != true) {
             $transformed = realpath($image);
             $hash = sha1_file($image);
         } else {
             $transformed = $image;
             $hash = sha1($image_data);
         }
         //Check if a version exists
         $cache_file = $this->cache_dir . sha1($transformed) . "." . $width . "." . $height . "." . $hash . "." . $this->file_ext[$format];
         if (file_exists($cache_file)) {
             if ($return_img == false) {
                 //die($cache_file);
                 header("Expires: " . gmdate("D, d M Y H:i:s") . " GMT");
                 header("Cache-Control: no-store, no-cache, must-revalidate");
                 header("Pragma: no-cache");
                 header("Content-Transfer-Encoding: binary");
                 header("Content-type: " . image_type_to_mime_type($format));
                 if ($display_inline == true) {
                     header("Content-Disposition: inline; filename=\"" . time() . "." . $this->file_ext[$format] . "\"");
                 } else {
                     header("Content-Disposition: attachment; filename=\"" . time() . "." . $this->file_ext[$format] . "\"");
                 }
                 print join(file($cache_file));
                 die;
                 //Prepare redirectional URL
                 $redir_url = $_SERVER["HTTP_HOST"] . dirname($_SERVER["PHP_SELF"]) . "/" . $cache_file;
                 //Remove instances of double slashes "//"
                 $redir_url = str_replace("//", "/", $redir_url);
                 header("Location: http://{$redir_url}");
                 die;
             } else {
                 return join(file($cache_file));
             }
         } else {
             if ($handle = @opendir($this->cache_dir)) {
                 while (false !== ($file = readdir($handle))) {
                     if (preg_match("/^" . preg_quote(sha1($transformed)) . "\\.[0-9]+\\.[0-9]+\\.([0-9a-z]{40})\\.(.+?)\$/i", $file, $matches)) {
                         //Hash is in [1]
                         //Check to see if the file data is the same. If it is, then don't delete it.
                         if ($matches[1] != $hash) {
                             $matched[] = $file;
                         }
                     }
                 }
                 closedir($handle);
                 if (!empty($matched)) {
                     for ($i = 0; $i <= count($matched) - 1; $i++) {
                         @unlink($this->cache_dir . $matched[$i]);
                     }
                 }
             }
         }
     }
     $gd_info = gd_info();
     //Special GIF handling
     if ($format == 1 && $gd_info["GIF Create Support"] != true) {
         //return $this -> set_error("Method print_thumbnail: Error, GIF support is unavaliable for PHP Version ".phpversion());
         //Image Outputted will be in PNG Format
         $format = 3;
     }
     $handle = @imagecreatefromstring($image_data);
     if ($handle == false) {
         return $this->set_error("Method print_thumbnail: Unsupported Image '{$image}' type");
     }
     //Now lets resize it
     //First lets create a new image handler which will be the thumbnailed image
     $thumbnail = imagecreatetruecolor($width, $height);
     if (!$thumbnail) {
         return $this->set_error("Method print_thumbnail: A thumbnail image '{$image}' could not be created");
     }
     /*  Image Format Special Handlinng */
     //GIF truecolour to palette - preserve transparency
     if ($format == 1) {
         imagetruecolortopalette($handle, true, 256);
     }
     //PNG Alpha Channel saving
     if ($format == 3) {
         //Set to save alpha channel info in source and destination
         imagealphablending($handle, false);
         imagesavealpha($handle, true);
         imagealphablending($thumbnail, false);
         imagesavealpha($thumbnail, true);
     }
     //Resize it
     if (!$this->fastimagecopyresampled($thumbnail, $handle, 0, 0, 0, 0, $width, $height, ImageSX($handle), ImageSY($handle), $this->thumb_quality)) {
         return $this->set_error("Method print_thumbnail: Failed resizing image '{$image}'.");
     }
     //Cache it
     if ($this->is_cacheable()) {
         switch ($format) {
             case 1:
                 $cached = @imagegif($thumbnail, $cache_file);
                 break;
             case 2:
                 $cached = @imageJPEG($thumbnail, $cache_file, 100);
                 break;
             case 3:
                 $cached = @imagepng($thumbnail, $cache_file);
                 break;
             case 15:
                 $cached = @imagewbmp($thumbnail, $cache_file);
                 break;
             case 16:
                 $cached = @imagexbm($thumbnail, $cache_file);
                 break;
             default:
                 $cached = false;
         }
         if (!$cached) {
             return $this->set_error("Method print_thumbnail: Error in cache generation of image '{$image}'.");
         }
     }
     if ($return_img == false) {
         header("Expires: " . gmdate("D, d M Y H:i:s") . " GMT");
         header("Cache-Control: no-store, no-cache, must-revalidate");
         header("Pragma: no-cache");
         header("Content-Transfer-Encoding: binary");
         header("Content-type: " . image_type_to_mime_type($format));
         if ($display_inline == true) {
             header("Content-Disposition: inline; filename=\"" . time() . "." . $this->file_ext[$format] . "\"");
         } else {
             header("Content-Disposition: attachment; filename=\"" . time() . "." . $this->file_ext[$format] . "\"");
         }
         if ($this->is_cacheable()) {
             echo join(file($cache_file));
         } else {
             switch ($format) {
                 case 1:
                     $outputed = @imagegif($thumbnail);
                     break;
                 case 2:
                     $outputed = @imageJPEG($thumbnail, '', 100);
                     break;
                 case 3:
                     $outputed = @imagepng($thumbnail);
                     break;
                 case 15:
                     $outpupted = @imagewbmp($thumbnail);
                     break;
                 case 16:
                     $outputed = @imagexbm($thumbnail);
                     break;
                 default:
                     $outputed = false;
             }
             if (!$outputed) {
                 return $this->set_error("Method print_thumbnail: Error outputting Image '{$image}'");
             }
         }
     } else {
         if ($this->is_cacheable()) {
             return join(file($cache_file));
         } else {
             return $this->set_error("Method print_thumbnail: Cannot return image '{$image}'! Cache must be enabled!");
         }
     }
     //Destroy the image
     imagedestroy($handle);
     imagedestroy($thumbnail);
     //Clear any cache; if needed
     $this->clear_cache();
 }
 /**
  * Saves the image to a given filename, if no filename is given then a default is created.
  *
  * @param string $save The new image filename.
  */
 public function save($save = "")
 {
     //save thumb
     if (empty($save)) {
         $save = strtolower("./thumb." . $this->image["outputformat"]);
     } else {
         $this->image["outputformat"] = preg_replace("/.*\\.(.*)\$/", "\\1", $save);
         //$this->image["outputformat"] = preg_replace(".*\.(.*)$", "\\1", $save);
         $this->image["outputformat"] = strtoupper($this->image["outputformat"]);
     }
     $this->createResampledImage();
     if ($this->image["outputformat"] == "JPG" || $this->image["outputformat"] == "JPEG") {
         //JPEG
         imageJPEG($this->image["des"], $save, $this->image["quality"]);
     } elseif ($this->image["outputformat"] == "PNG") {
         //PNG
         imagePNG($this->image["des"], $save, 0);
     } elseif ($this->image["outputformat"] == "GIF") {
         //GIF
         imageGIF($this->image["des"], $save);
     } elseif ($this->image["outputformat"] == "WBMP") {
         //WBMP
         imageWBMP($this->image["des"], $save);
     }
 }
 function generateImage($save = '', $show = true)
 {
     if ($this->img["format"] == "GIF" && !$this->gifsupport) {
         // --- kein caching -> gif ausgeben
         Header("Content-Type: image/" . $this->img["format"]);
         readfile($this->imgfile);
         exit;
     }
     $this->resampleImage();
     if ($this->img["format"] == "JPG" || $this->img["format"] == "JPEG") {
         imageJPEG($this->img["des"], $save, $this->img["quality"]);
     } elseif ($this->img["format"] == "PNG") {
         imagePNG($this->img["des"], $save);
     } elseif ($this->img["format"] == "GIF") {
         imageGIF($this->img["des"], $save);
     } elseif ($this->img["format"] == "WBMP") {
         imageWBMP($this->img["des"], $save);
     }
     if ($show) {
         Header("Content-Type: image/" . $this->img["format"]);
         readfile($save);
     }
 }
Esempio n. 27
0
 /**
  * Creates a new image given an original path, a new path, a target width and height.
  * Optionally crops image to exactly match given width and height.
  * @params string $originalPath, string $newpath, int $width, int $height, bool $crop
  * @return void
  */
 public function create($originalPath, $newPath, $width, $height, $crop = false)
 {
     // first, we grab the original image. We shouldn't ever get to this function unless the image is valid
     $imageSize = @getimagesize($originalPath);
     $oWidth = $imageSize[0];
     $oHeight = $imageSize[1];
     $finalWidth = 0;
     //For cropping, this is really "scale to width before chopping extra height"
     $finalHeight = 0;
     //For cropping, this is really "scale to height before chopping extra width"
     $do_crop_x = false;
     $do_crop_y = false;
     $crop_src_x = 0;
     $crop_src_y = 0;
     // first, if what we're uploading is actually smaller than width and height, we do nothing
     if ($oWidth < $width && $oHeight < $height) {
         $finalWidth = $oWidth;
         $finalHeight = $oHeight;
         $width = $oWidth;
         $height = $oHeight;
     } else {
         if ($crop && ($height >= $oHeight && $width <= $oWidth)) {
             //crop to width only -- don't scale anything
             $finalWidth = $oWidth;
             $finalHeight = $oHeight;
             $height = $oHeight;
             $do_crop_x = true;
         } else {
             if ($crop && ($width >= $oWidth && $height <= $oHeight)) {
                 //crop to height only -- don't scale anything
                 $finalHeight = $oHeight;
                 $finalWidth = $oWidth;
                 $width = $oWidth;
                 $do_crop_y = true;
             } else {
                 // otherwise, we do some complicated stuff
                 // first, we divide original width and height by new width and height, and find which difference is greater
                 $wDiff = $oWidth / $width;
                 $hDiff = $oHeight / $height;
                 if (!$crop && $wDiff > $hDiff) {
                     //no cropping, just resize down based on target width
                     $finalWidth = $width;
                     $finalHeight = $oHeight / $wDiff;
                 } else {
                     if (!$crop) {
                         //no cropping, just resize down based on target height
                         $finalWidth = $oWidth / $hDiff;
                         $finalHeight = $height;
                     } else {
                         if ($crop && $wDiff > $hDiff) {
                             //resize down to target height, THEN crop off extra width
                             $finalWidth = $oWidth / $hDiff;
                             $finalHeight = $height;
                             $do_crop_x = true;
                         } else {
                             if ($crop) {
                                 //resize down to target width, THEN crop off extra height
                                 $finalWidth = $width;
                                 $finalHeight = $oHeight / $wDiff;
                                 $do_crop_y = true;
                             }
                         }
                     }
                 }
             }
         }
     }
     //Calculate cropping to center image
     if ($do_crop_x) {
         /*
         //Get half the difference between scaled width and target width,
         // and crop by starting the copy that many pixels over from the left side of the source (scaled) image.
         $nudge = ($width / 10); //I have *no* idea why the width isn't centering exactly -- this seems to fix it though.
         $crop_src_x = ($finalWidth / 2.00) - ($width / 2.00) + $nudge;
         */
         $crop_src_x = round(($oWidth - $width * $oHeight / $height) * 0.5);
     }
     if ($do_crop_y) {
         /*
         //Calculate cropping...
         //Get half the difference between scaled height and target height,
         // and crop by starting the copy that many pixels down from the top of the source (scaled) image.
         $crop_src_y = ($finalHeight / 2.00) - ($height / 2.00);
         */
         $crop_src_y = round(($oHeight - $height * $oWidth / $width) * 0.5);
     }
     //create "canvas" to put new resized and/or cropped image into
     if ($crop) {
         $image = @imageCreateTrueColor($width, $height);
     } else {
         $image = @imageCreateTrueColor($finalWidth, $finalHeight);
     }
     switch ($imageSize[2]) {
         case IMAGETYPE_GIF:
             $im = @imageCreateFromGIF($originalPath);
             break;
         case IMAGETYPE_JPEG:
             $im = @imageCreateFromJPEG($originalPath);
             break;
         case IMAGETYPE_PNG:
             $im = @imageCreateFromPNG($originalPath);
             break;
     }
     if ($im) {
         // Better transparency - thanks for the ideas and some code from mediumexposure.com
         if ($imageSize[2] == IMAGETYPE_GIF || $imageSize[2] == IMAGETYPE_PNG) {
             $trnprt_indx = imagecolortransparent($im);
             // If we have a specific transparent color
             if ($trnprt_indx >= 0) {
                 // Get the original image's transparent color's RGB values
                 $trnprt_color = imagecolorsforindex($im, $trnprt_indx);
                 // Allocate the same color in the new image resource
                 $trnprt_indx = imagecolorallocate($image, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
                 // Completely fill the background of the new image with allocated color.
                 imagefill($image, 0, 0, $trnprt_indx);
                 // Set the background color for new image to transparent
                 imagecolortransparent($image, $trnprt_indx);
             } else {
                 if ($imageSize[2] == IMAGETYPE_PNG) {
                     // Turn off transparency blending (temporarily)
                     imagealphablending($image, false);
                     // Create a new transparent color for image
                     $color = imagecolorallocatealpha($image, 0, 0, 0, 127);
                     // Completely fill the background of the new image with allocated color.
                     imagefill($image, 0, 0, $color);
                     // Restore transparency blending
                     imagesavealpha($image, true);
                 }
             }
         }
         $res = @imageCopyResampled($image, $im, 0, 0, $crop_src_x, $crop_src_y, $finalWidth, $finalHeight, $oWidth, $oHeight);
         if ($res) {
             switch ($imageSize[2]) {
                 case IMAGETYPE_GIF:
                     $res2 = imageGIF($image, $newPath);
                     break;
                 case IMAGETYPE_JPEG:
                     $compression = defined('AL_THUMBNAIL_JPEG_COMPRESSION') ? AL_THUMBNAIL_JPEG_COMPRESSION : 80;
                     $res2 = imageJPEG($image, $newPath, $compression);
                     break;
                 case IMAGETYPE_PNG:
                     $res2 = imagePNG($image, $newPath);
                     break;
             }
         }
     }
 }
Esempio n. 28
0
 function ImageResize_Ex($o_file, $newPath, $img_width, $img_height, $ext)
 {
     $image_info = getImageSize($o_file);
     // see EXIF for faster way
     $srcWidth = $image_info[0];
     $srcHeight = $image_info[1];
     $destWidth = $srcWidth;
     $destHeight = $srcHeight;
     $crop_x = 0;
     $crop_y = 0;
     $percent = 0.0;
     if ($srcWidth > $img_width) {
         $destWidth = $img_width;
         $percent = $destWidth / $srcWidth;
         $destHeight = $srcHeight * $percent;
     }
     $o_im = @ImageCreateFromJPEG($o_file);
     //$this->LoadImage($o_file, $ext) ;
     if ($o_im == false) {
         echo "=---error image----";
     }
     $t_im = imageCreateTrueColor($destWidth, $destHeight);
     imagecopyresampled($t_im, $o_im, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
     if ($ext == ".jpg" or $ext == ".jpeg") {
         imageJPEG($t_im, $newPath, 100);
     } else {
         if ($ext == ".png") {
             imagepng($t_im, $newPath);
             /* Attempt to open */
         } else {
             if ($ext == ".gif") {
                 imagegif($t_im, $newPath);
             }
         }
     }
     imageDestroy($o_im);
     imageDestroy($t_im);
 }
Esempio n. 29
0
 /**
  * Write the image after being processed
  *
  * @param Asido_TMP &$tmp
  * @return boolean
  * @access protected
  */
 function __write(&$tmp)
 {
     // try to guess format from extension
     //
     if (!$tmp->save) {
         $p = pathinfo($tmp->target_filename);
         ($tmp->save = $this->__mime_metaphone[metaphone($p['extension'])]) || ($tmp->save = $this->__mime_soundex[soundex($p['extension'])]);
     }
     $result = false;
     $imgContent = null;
     switch ($tmp->save) {
         case 'image/gif':
             imageTrueColorToPalette($tmp->target, true, 256);
             ob_start();
             $result = @imageGIF($tmp->target);
             $imgContent = ob_get_clean();
             break;
         case 'image/jpeg':
             ob_start();
             $result = @imageJPEG($tmp->target, null, ASIDO_GD_JPEG_QUALITY);
             $imgContent = ob_get_clean();
             break;
         case 'image/wbmp':
             ob_start();
             $result = @imageWBMP($tmp->target);
             $imgContent = ob_get_clean();
             break;
         default:
         case 'image/png':
             imageSaveAlpha($tmp->target, true);
             imageAlphaBlending($tmp->target, false);
             ob_start();
             $result = @imagePNG($tmp->target, null, ASIDO_GD_PNG_QUALITY);
             $imgContent = ob_get_clean();
             break;
     }
     if ($result) {
         jimport('joomla.filesystem.file');
         JFile::write($tmp->target_filename, $imgContent);
     }
     @$this->__destroy_source($tmp);
     @$this->__destroy_target($tmp);
     return $result;
 }
	public function edit($path, $crop_x, $crop_y, $crop_w, $crop_h, $target_w, $target_h) {
		$imageSize = @getimagesize($path);
		$img_type = $imageSize[2];
		
		//create "canvas" to put new resized and/or cropped image into
		$image = @imageCreateTrueColor($target_w, $target_h);
		
		switch($img_type) {
			case IMAGETYPE_GIF:
				$im = @imageCreateFromGIF($path);
				break;
			case IMAGETYPE_JPEG:
				$im = @imageCreateFromJPEG($path);
				break;
			case IMAGETYPE_PNG:
				$im = @imageCreateFromPNG($path);
				break;
		}
		
		if ($im) {
			// Better transparency - thanks for the ideas and some code from mediumexposure.com
			if (($img_type == IMAGETYPE_GIF) || ($img_type == IMAGETYPE_PNG)) {
				$trnprt_indx = imagecolortransparent($im);
				
				// If we have a specific transparent color
				if ($trnprt_indx >= 0) {
			
					// Get the original image's transparent color's RGB values
					$trnprt_color = imagecolorsforindex($im, $trnprt_indx);
					
					// Allocate the same color in the new image resource
					$trnprt_indx = imagecolorallocate($image, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
					
					// Completely fill the background of the new image with allocated color.
					imagefill($image, 0, 0, $trnprt_indx);
					
					// Set the background color for new image to transparent
					imagecolortransparent($image, $trnprt_indx);
					
				
				} else if ($img_type == IMAGETYPE_PNG) {
				
					// Turn off transparency blending (temporarily)
					imagealphablending($image, false);
					
					// Create a new transparent color for image
					$color = imagecolorallocatealpha($image, 0, 0, 0, 127);
					
					// Completely fill the background of the new image with allocated color.
					imagefill($image, 0, 0, $color);
					
					// Restore transparency blending
					imagesavealpha($image, true);
			
				}
			}
			
			$res = @imageCopyResampled($image, $im, 0, 0, $crop_x, $crop_y, $target_w, $target_h, $crop_w, $crop_h);
			if ($res) {
				switch($img_type) {
					case IMAGETYPE_GIF:
						$res2 = imageGIF($image, $path);
						break;
					case IMAGETYPE_JPEG:
						$compression = defined('AL_THUMBNAIL_JPEG_COMPRESSION') ? AL_THUMBNAIL_JPEG_COMPRESSION : 80;
						$res2 = imageJPEG($image, $path, $compression);
						break;
					case IMAGETYPE_PNG:
						$res2 = imagePNG($image, $path);
						break;
				}
			}
		}
	}