function imageCreateFromAny($filepath) { list($w, $h, $t, $attr) = getimagesize($filepath); // [] if you don't have exif you could use getImageSize() $allowedTypes = array(IMG_GIF, IMG_JPG, IMG_PNG, IMG_WBMP); if (!in_array($t, $allowedTypes)) { return false; } switch ($t) { case IMG_GIF: $im = imageCreateFromGif($filepath); echo 'type image GIF'; break; case IMG_JPG: $im = imageCreateFromJpeg($filepath); echo 'type image JPG'; break; case IMG_PNG: $im = imageCreateFromPng($filepath); echo 'type image PNG'; break; case IMG_WBMP: $im = imageCreateFromwBmp($filepath); echo 'type image BMP'; break; } echo 'source : ' . $filepath . ' | im : ' . $im; return $im; }
/** * Load image from $fileName * * @throws Zend_Image_Driver_Exception * @param string $fileName Path to image */ public function load($fileName) { parent::load($fileName); $this->_imageLoaded = false; $info = getimagesize($fileName); switch ($this->_type) { case 'jpg': $this->_image = imageCreateFromJpeg($fileName); if ($this->_image !== false) { $this->_imageLoaded = true; } break; case 'png': $this->_image = imageCreateFromPng($fileName); if ($this->_image !== false) { $this->_imageLoaded = true; } break; case 'gif': $this->_image = imageCreateFromGif($fileName); if ($this->_image !== false) { $this->_imageLoaded = true; } break; } }
function image_createThumb($src, $dest, $maxWidth, $maxHeight, $quality = 75) { if (file_exists($src) && isset($dest)) { // path info $destInfo = pathInfo($dest); // image src size $srcSize = getImageSize($src); // image dest size $destSize[0] = width, $destSize[1] = height $srcRatio = $srcSize[0] / $srcSize[1]; // width/height ratio $destRatio = $maxWidth / $maxHeight; if ($destRatio > $srcRatio) { $destSize[1] = $maxHeight; $destSize[0] = $maxHeight * $srcRatio; } else { $destSize[0] = $maxWidth; $destSize[1] = $maxWidth / $srcRatio; } // path rectification if ($destInfo['extension'] == "gif") { $dest = substr_replace($dest, 'jpg', -3); } // true color image, with anti-aliasing $destImage = imageCreateTrueColor($destSize[0], $destSize[1]); // imageAntiAlias($destImage,true); // src image switch ($srcSize[2]) { case 1: //GIF $srcImage = imageCreateFromGif($src); break; case 2: //JPEG $srcImage = imageCreateFromJpeg($src); break; case 3: //PNG $srcImage = imageCreateFromPng($src); break; default: return false; break; } // resampling imageCopyResampled($destImage, $srcImage, 0, 0, 0, 0, $destSize[0], $destSize[1], $srcSize[0], $srcSize[1]); // generating image switch ($srcSize[2]) { case 1: case 2: imageJpeg($destImage, $dest, $quality); break; case 3: imagePng($destImage, $dest); break; } return true; } else { return 'No such File'; } }
protected function get_any_type($srcpath) { try { $this->check_file($srcpath); $srcSize = getImageSize($srcpath); switch ($srcSize[2]) { case 1: $img = imageCreateFromGif($srcpath); break; case 2: $img = imageCreateFromJpeg($srcpath); break; case 3: $img = imageCreateFromPng($srcpath); break; default: throw new Imgdexception('not possible to get any type - srcpath:' . $srcpath); break; } $image['width'] = $srcSize[0]; $image['height'] = $srcSize[1]; $image['img'] = $img; return $image; } catch (Imgdexception $e) { $e->print_debug(__FILE__, __LINE__); return false; } }
function imageResize($file, $info, $destination) { $height = $info[1]; //высота $width = $info[0]; //ширина //определяем размеры будущего превью $y = 150; if ($width > $height) { $x = $y * ($width / $height); } else { $x = $y / ($height / $width); } $to = imageCreateTrueColor($x, $y); switch ($info['mime']) { case 'image/jpeg': $from = imageCreateFromJpeg($file); break; case 'image/png': $from = imageCreateFromPng($file); break; case 'image/gif': $from = imageCreateFromGif($file); break; default: echo "No prevue"; break; } imageCopyResampled($to, $from, 0, 0, 0, 0, imageSX($to), imageSY($to), imageSX($from), imageSY($from)); imagepng($to, $destination); imagedestroy($from); imagedestroy($to); }
/** * Using GD lib for get and transform images. * @see http://php.net/manual/en/function.imagecreatefromjpeg.php#110547 */ function anyImgFile2Im($fname = NULL) { if ($fname) { $this->setFile($fname); } $allowedTypes = [1, 2, 3, 6]; // gif,jpg,png,bmp if (!in_array($this->ftype, $allowedTypes)) { return false; } switch ($this->ftype) { case 1: $im = imageCreateFromGif($this->fname); break; case 2: $im = imageCreateFromJpeg($this->fname); break; case 3: $im = imageCreateFromPng($this->fname); // echo "\n degug {$this->fname}"; break; case 6: $im = imageCreateFromBmp($this->fname); break; } return $im; }
function load() { if ($this->loaded) { return true; } //$size = $this->get_size(); //if (!$size) throw new exception("Failed loading image"); list($this->w, $this->h, $this->type) = getImageSize($this->src); switch ($this->type) { case 1: $this->img = imageCreateFromGif($this->src); break; case 2: $this->img = imageCreateFromJpeg($this->src); break; case 3: $this->img = imageCreateFromPng($this->src); break; default: throw new exception("Unsuported image type"); break; } $this->loaded = true; return true; }
/** * Read a gif image from file * @param File file of the image * @return resource internal PHP image resource of the file */ public function read(File $file) { $this->checkIfReadIsPossible($file, 'gif'); $image = imageCreateFromGif($file->getAbsolutePath()); if ($image === false) { throw new ImageException($file->getPath() . ' is not a valid GIF image'); } return $image; }
function img_create($type, $name) { if ($type == "gif") { $im = imageCreateFromGif($name); } elseif ($type == "jpeg" || $type == "jpg") { $im = imagecreatefromjpeg($name); } elseif ($type == "png") { $im = imageCreateFromPng($name); } elseif ($type == "bmp") { $im = imageCreateFromBmp($name); } else { return false; } return $im; }
/** * @see \wcf\system\image\adapter\IImageAdapter::loadFile() */ public function loadFile($file) { list($this->width, $this->height, $this->type) = getImageSize($file); switch ($this->type) { case IMAGETYPE_GIF: $this->image = imageCreateFromGif($file); break; case IMAGETYPE_JPEG: $this->image = imageCreateFromJpeg($file); break; case IMAGETYPE_PNG: $this->image = imageCreateFromPng($file); break; default: throw new SystemException("Could not read image '" . $file . "', format is not recognized."); break; } }
function loadImage($path) { if ($this->image) { imagedestroy($this->image); } $img_sz = getimagesize($path); switch ($img_sz[2]) { case 1: $this->image_type = "GIF"; if (!($this->image = imageCreateFromGif($path))) { return FALSE; } else { return TRUE; } break; case 2: $this->image_type = "JPG"; if (!($this->image = imageCreateFromJpeg($path))) { return FALSE; } else { return TRUE; } break; case 3: $this->image_type = "PNG"; if (!($this->image = imageCreateFromPng($path))) { return FALSE; } else { return TRUE; } break; case 4: $this->image_type = "SWF"; if (!($this->image = imageCreateFromSwf($path))) { return FALSE; } else { return TRUE; } break; default: return FALSE; } }
function __construct($filename) { $this->_filename = $filename; list($this->_width, $this->_height) = getimagesize($this->_filename); $pathinfo = pathinfo($filename); switch (strtolower($pathinfo['extension'])) { case 'jpg': case 'jpeg': $this->_source = imageCreateFromJpeg($filename); break; case 'gif': $this->_source = imageCreateFromGif($filename); $this->_createImageCallback = 'imagecreate'; break; case 'png': $this->_source = imageCreateFromPng($filename); break; default: throw new Naf_Image_Exception('Unsupported file extension'); break; } }
private function imageResize($image, $width, $height, $name) { $ifile = $image['tmp_name']; $isize = getImageSize($ifile); $iw = $isize[0]; $ih = $isize[1]; switch ($image['type']) { case "image/gif": $img = imageCreateFromGif($ifile); break; case "image/jpeg": $img = imageCreateFromJpeg($ifile); break; case "image/png": $img = imageCreateFromPng($ifile); break; case "image/pjpeg": $img = imageCreateFromJpeg($ifile); break; case "image/x-png": $img = imageCreateFromPng($ifile); break; } if ($iw > $ih) { $new_ih = $ih / ($iw / $width); $new_iw = $width; } else { $new_iw = $iw / ($ih / $height); $new_ih = $height; } $dst = imageCreateTrueColor($new_iw, $new_ih); imageCopyResampled($dst, $img, 0, 0, 0, 0, $new_iw, $new_ih, $iw, $ih); imagePNG($dst, $name, 0); imageDestroy($img); imageDestroy($dst); }
function create_image_from_any($filepath) { $type = exif_imagetype($filepath); // [] if you don't have exif you could use getImageSize() //echo $type; exit; $allowedTypes = array(1, 2, 3); if (!in_array($type, $allowedTypes)) { return false; } switch ($type) { case 1: $image = imageCreateFromGif($filepath); break; case 2: $image = imageCreateFromJpeg($filepath); break; case 3: $image = imageCreateFromPng($filepath); break; // case 6 : // $image = imageCreateFromBmp($filepath); // break; } return $image; }
/** * Generate images of alternate sizes. */ function resizeImage($cnvrt_arry) { global $platform, $imgs, $cnvrt_path, $reqd_image, $convert_writable, $convert_magick, $convert_GD, $convert_cmd, $cnvrt_alt, $cnvrt_mesgs, $compat_quote; if (empty($imgs) || $convert_writable == FALSE) { return; } if ($convert_GD == TRUE && !($gd_version = gdVersion())) { return; } if ($cnvrt_alt['no_prof'] == TRUE) { $strip_prof = ' +profile "*"'; } else { $strip_prof = ''; } if ($cnvrt_alt['mesg_on'] == TRUE) { $str = ''; } foreach ($imgs as $img_file) { if ($cnvrt_alt['indiv'] == TRUE && $img_file != $reqd_image['file']) { continue; } $orig_img = $reqd_image['pwd'] . '/' . $img_file; $cnvrtd_img = $cnvrt_path . '/' . $cnvrt_arry['prefix'] . $img_file; if (!is_file($cnvrtd_img)) { $img_size = GetImageSize($orig_img); $height = $img_size[1]; $width = $img_size[0]; $area = $height * $width; $maxarea = $cnvrt_arry['maxwid'] * $cnvrt_arry['maxwid'] * 0.9; $maxheight = $cnvrt_arry['maxwid'] * 0.75 + 1; if ($area > $maxarea || $width > $cnvrt_arry['maxwid'] || $height > $maxheight) { if ($width / $cnvrt_arry['maxwid'] >= $height / $maxheight) { $dim = 'W'; } if ($height / $maxheight >= $width / $cnvrt_arry['maxwid']) { $dim = 'H'; } if ($dim == 'W') { $cnvt_percent = round(0.9375 * $cnvrt_arry['maxwid'] / $width * 100, 2); } if ($dim == 'H') { $cnvt_percent = round(0.75 * $cnvrt_arry['maxwid'] / $height * 100, 2); } // convert it if ($convert_magick == TRUE) { // Image Magick image conversion if ($platform == 'Win32' && $compat_quote == TRUE) { $winquote = '"'; } else { $winquote = ''; } exec($winquote . $convert_cmd . ' -geometry ' . $cnvt_percent . '%' . ' -quality ' . $cnvrt_arry['qual'] . ' -sharpen ' . $cnvrt_arry['sharpen'] . $strip_prof . ' "' . $orig_img . '"' . ' "' . $cnvrtd_img . '"' . $winquote); $using = $cnvrt_mesgs['using IM']; } elseif ($convert_GD == TRUE) { // GD image conversion if (eregi('\\.jpg$|\\.jpeg$', $img_file) == TRUE && (imageTypes() & IMG_JPG) == TRUE) { $src_img = imageCreateFromJpeg($orig_img); } elseif (eregi('\\.gif$', $img_file) == TRUE && (imageTypes() & IMG_PNG) == TRUE) { $src_img = imageCreateFromPng($orig_img); } elseif (eregi('\\.gif$', $img_file) == TRUE && (imageTypes() & IMG_GIF) == TRUE) { $src_img = imageCreateFromGif($orig_img); } else { continue; } $src_width = imageSx($src_img); $src_height = imageSy($src_img); $dest_width = $src_width * ($cnvt_percent / 100); $dest_height = $src_height * ($cnvt_percent / 100); if ($gd_version >= 2) { $dst_img = imageCreateTruecolor($dest_width, $dest_height); imageCopyResampled($dst_img, $src_img, 0, 0, 0, 0, $dest_width, $dest_height, $src_width, $src_height); } else { $dst_img = imageCreate($dest_width, $dest_height); imageCopyResized($dst_img, $src_img, 0, 0, 0, 0, $dest_width, $dest_height, $src_width, $src_height); } imageDestroy($src_img); if (eregi('\\.jpg$|\\.jpeg$/i', $img_file) == TRUE && (imageTypes() & IMG_JPG) == TRUE) { imageJpeg($dst_img, $cnvrtd_img, $cnvrt_arry['qual']); } elseif (eregi('\\.gif$', $img_file) == TRUE && (imageTypes() & IMG_PNG) == TRUE) { imagePng($dst_img, $cnvrtd_img); } elseif (eregi('\\.gif$/i', $img_file) == TRUE && (imageTypes() & IMG_GIF) == TRUE) { imageGif($dst_img, $cnvrtd_img); } imageDestroy($dst_img); $using = $cnvrt_mesgs['using GD'] . $gd_version; } if ($cnvrt_alt['mesg_on'] == TRUE && is_file($cnvrtd_img)) { $str .= " <small>\n" . ' ' . $cnvrt_mesgs['generated'] . $cnvrt_arry['txt'] . $cnvrt_mesgs['converted'] . $cnvrt_mesgs['image_for'] . $img_file . $using . ".\n" . " </small>\n <br />\n"; } } } } if (isset($str)) { return $str; } }
<?php ## Создание картинки "на лету". // Получаем строку, которую нам передали в параметрах $string = $_SERVER['QUERY_STRING'] ?? "Hello, world!"; // Загружаем рисунок фона с диска. $im = imageCreateFromGif("button.gif"); // Создаем в палитре новый цвет - черный. $color = imageColorAllocate($im, 0, 0, 0); // Вычисляем размеры текста, который будет выведен. $px = (imageSX($im) - 6.5 * strlen($string)) / 2; // Выводим строку поверх того, что было в загруженном изображении. imageString($im, 3, $px, 1, $string, $color); // Сообщаем о том, что далее следует рисунок PNG. header("Content-type: image/png"); // Теперь - самое главное: отправляем данные картинки в // стандартный выходной поток, т. е. в браузер. imagePng($im); // В конце освобождаем память, занятую картинкой. imageDestroy($im);
function imageCreateFromImg( $filename ) { $split = split( "\.", basename( trim( $filename ) ) ); $ext = $split[ count($split) - 1 ] ; switch( strtolower( $ext ) ) { case "gif" : return imageCreateFromGif( $filename ); break; case "png" : return imagecreatefrompng( $filename ); break; case "jpg" : case "jpeg" : return imagecreatefromjpeg( $filename ); break; } }
/** * Creates a new GDlib image resource based on the input image filename. * If it fails creating an image from the input file a blank gray image with the dimensions of the input image will be created instead. * * @param string $sourceImg Image filename * @return resource Image Resource pointer */ public function imageCreateFromFile($sourceImg) { $imgInf = pathinfo($sourceImg); $ext = strtolower($imgInf['extension']); switch ($ext) { case 'gif': if (function_exists('imagecreatefromgif')) { return imageCreateFromGif($sourceImg); } break; case 'png': if (function_exists('imagecreatefrompng')) { $imageHandle = imageCreateFromPng($sourceImg); if ($this->saveAlphaLayer) { imagesavealpha($imageHandle, true); } return $imageHandle; } break; case 'jpg': case 'jpeg': if (function_exists('imagecreatefromjpeg')) { return imageCreateFromJpeg($sourceImg); } break; } // If non of the above: $i = @getimagesize($sourceImg); $im = imagecreatetruecolor($i[0], $i[1]); $Bcolor = ImageColorAllocate($im, 128, 128, 128); ImageFilledRectangle($im, 0, 0, $i[0], $i[1], $Bcolor); return $im; }
/** * Compressing a GIF file if not already LZW compressed. * This function is a workaround for the fact that ImageMagick and/or GD does not compress GIF-files to their minimun size (that is RLE or no compression used) * * The function takes a file-reference, $theFile, and saves it again through GD or ImageMagick in order to compress the file * GIF: * If $type is not set, the compression is done with ImageMagick (provided that $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'] is pointing to the path of a lzw-enabled version of 'convert') else with GD (should be RLE-enabled!) * If $type is set to either 'IM' or 'GD' the compression is done with ImageMagick and GD respectively * PNG: * No changes. * * $theFile is expected to be a valid GIF-file! * The function returns a code for the operation. * Usage: 9 * * @param string Filepath * @param string See description of function * @return string Returns "GD" if GD was used, otherwise "IM" if ImageMagick was used. If nothing done at all, it returns empty string. */ public static function gif_compress($theFile, $type) { $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX']; $returnCode = ''; if ($gfxConf['gif_compress'] && strtolower(substr($theFile, -4, 4)) == '.gif') { // GIF... if (($type == 'IM' || !$type) && $gfxConf['im'] && $gfxConf['im_path_lzw']) { // IM $cmd = self::imageMagickCommand('convert', '"' . $theFile . '" "' . $theFile . '"', $gfxConf['im_path_lzw']); exec($cmd); $returnCode = 'IM'; } elseif (($type == 'GD' || !$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png']) { // GD $tempImage = imageCreateFromGif($theFile); imageGif($tempImage, $theFile); imageDestroy($tempImage); $returnCode = 'GD'; } } return $returnCode; }
function getImageType($file) { //使用getimagesize()函数,返回图像相关数据 file_exists($file) ? $TempImage = getimagesize($file) : die("文件不存在!"); switch ($TempImage[2]) { case 1: $image = imageCreateFromGif($file); $this->_type = "gif"; break; case 2: $image = imageCreateFromJpeg($file); $this->_type = "jpg"; break; case 3: $image = imageCreateFromPng($file); $this->_type = "png"; break; default: die("不支持该文件格式,请使用GIF、JPG、PNG格式。"); } unset($TempImage); $this->_im = $image; }
break; case "png": header('Content-type: image/png'); $cache = imageCreateFromPng($cache_path); imagePng($cache); break; } exit; } if (!file_exists($image_path)) { //header("location: $path"); exit; } switch ($ext) { case "gif": $img = imageCreateFromGif($image_path); break; case "jpg": $img = imageCreateFromJpeg($image_path); break; case "jpeg": $img = imageCreateFromJpeg($image_path); break; case "png": $img = imageCreateFromPng($image_path); break; default: $img = null; break; } if ($img == null) {
/** Cắt ảnh theo cỡ tùy chọn */ function create_image($args) { $hmdb = new MySQL(true, DB_NAME, DB_HOST, DB_USER, DB_PASSWORD, DB_CHARSET); hook_filter('before_create_image', $args); hook_action('create_image'); if (!is_array($args)) { parse_str($args, $args); } $file_id = $args['file']; if (isset_image($file_id)) { $row = get_file_data($file_id); $file_info = json_decode($row->file_info); $file_dst_name_body = $file_info->file_dst_name_body; $file_dst_name_ext = $file_info->file_dst_name_ext; $source_file = get_file_location($file_id); $crop_name = $file_dst_name_body . '-' . $args['w'] . 'x' . $args['h'] . '.' . $file_dst_name_ext; if (file_exists(get_file_location($file_id, FALSE) . $crop_name)) { return get_file_url($file_id, FALSE) . $crop_name; } else { /** resize file */ /* fix func exif_imagetype not avaiable */ $type = getimagesize($source_file); $type = $type['mime']; switch ($type) { case 'image/png': $type = IMAGETYPE_PNG; break; case 'image/jpeg': $type = IMAGETYPE_JPEG; break; case 'image/gif': $type = IMAGETYPE_GIF; break; case 'image/bmp': $type = IMAGETYPE_BMP; break; case 'image/x-ms-bmp': $type = IMAGETYPE_BMP; break; } /* fix func exif_imagetype not avaiable */ switch ($type) { case 1: $source = imageCreateFromGif($source_file); break; case 2: $source = imageCreateFromJpeg($source_file); break; case 3: $source = imageCreateFromPng($source_file); break; case 6: $source = imageCreateFromBmp($source_file); break; } /** resize file gốc về cùng 1 cỡ */ $size = getimagesize($source_file); $source_width = $size[0]; $source_height = $size[1]; $fix_width = $args['w']; $fix_height = $args['h']; $thumb = imagecreatetruecolor($fix_width, $fix_height); /* Fix black background */ $white = imagecolorallocate($thumb, 255, 255, 255); imagefill($thumb, 0, 0, $white); /* Fix black background */ /* fix quality with imagecopyresampled , repalce imagecopyresized */ imagecopyresampled($thumb, $source, 0, 0, 0, 0, $fix_width, $fix_height, $source_width, $source_height); $saveto = get_file_location($file_id, FALSE) . $crop_name; imagejpeg($thumb, $saveto, 100); return get_file_url($file_id, FALSE) . $crop_name; } } else { return FALSE; } }
public static function convert($srcFile = null, $destFile = null, $width = 0, $height = 0, $mode = self::MODE_CUT) { if (false === file_exists($srcFile)) { return false; } preg_match('/\\.([^\\.]+)$/', $destFile, $matches); switch (strtolower($matches[1])) { case 'jpg': case 'jpeg': $saveType = self::TYPE_JPG; break; case 'gif': $saveType = self::TYPE_GIF; break; case 'png': $saveType = self::TYPE_PNG; break; default: $saveType = self::TYPE_JPG; } $type = self::getImageType($srcFile); $srcImage = null; switch ($type) { case self::TYPE_GIF: $srcImage = imageCreateFromGif($srcFile); break; case self::TYPE_JPG: $srcImage = imageCreateFromJpeg($srcFile); break; case self::TYPE_PNG: $srcImage = imageCreateFromPng($srcFile); break; default: return false; } $srcWidth = imageSX($srcImage); $srcHeight = imageSY($srcImage); if ($width == 0 && $height == 0) { $width = $srcWidth; $height = $srcHeight; $mode = self::MODE_SCALE; } else { if ($width > 0 & $height == 0) { $useWidth = true; $mode = self::MODE_SCALE; if ($srcWidth <= $width) { return self::saveFile($srcImage, $destFile, $saveType); } } else { if ($width == 0 && $height > 0) { $mode = self::MODE_SCALE; } } } if ($mode == self::MODE_SCALE) { if ($width > 0 & $height > 0) { $useWidth = $srcWidth * $height > $srcHeight * $width ? true : false; } if (isset($useWidth) && $useWidth == true) { $height = $srcHeight * $width / $srcWidth; } else { $width = $srcWidth * $height / $srcHeight; } } $destImage = imageCreateTrueColor($width, $height); if ($mode == self::MODE_CUT) { $useWidth = $srcWidth * $height > $srcHeight * $width ? false : true; if ($useWidth == true) { $tempWidth = $width; $tempHeight = $srcHeight * $tempWidth / $srcWidth; } else { $tempHeight = $height; $tempWidth = $srcWidth * $tempHeight / $srcHeight; } $tempImage = imageCreateTrueColor($tempWidth, $tempHeight); $srcImage = imageCopyResampled($tempImage, $srcImage, 0, 0, 0, 0, $tempWidth, $tempHeight, $srcWidth, $srcHeight); imageDestroy($srcImage); $srcImage = $tempImage; $srcWidth = $width; $srcHeight = $srcWidth * $width / $srcHeight; } if ($mode == self::MODE_SCALE) { imageCopyResampled($destImage, $srcImage, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight); } else { imageCopyResampled($destImage, $srcImage, 0, 0, 0, 0, $width, $height, $width, $height); } @imageDestroy($srcImage); return self::saveFile($destImage, $destFile, $saveType); }
/** * This function resizes given image, if it has bigger dimensions, than we need and saves it (also makes chmod 0777 on the file) ... * It uses GD or ImageMagick, setting is available to change in CL's config file. * * @param string $inputFileName the input file to work with * @param string $outputFileName the file to write into the final (resized) image * @param integer $maxNewWidth maximal width of image * @param integer $maxNewHeight maximal height of image * @return bool TRUE, if everything was successful (resize and chmod), else FALSE */ function resize($inputFileName, $outputFileName, $maxNewWidth, $maxNewHeight) { $imageInfo = getimagesize($inputFileName); $fileType = $imageInfo['mime']; $extension = strtolower(str_replace('.', '', substr($outputFileName, -4))); $originalWidth = $imageInfo[0]; $originalHeight = $imageInfo[1]; if ($originalWidth > $maxNewWidth or $originalHeight > $maxNewHeight) { $newWidth = $maxNewWidth; $newHeight = $originalHeight / ($originalWidth / $maxNewWidth); if ($newHeight > $maxNewHeight) { $newHeight = $maxNewHeight; $newWidth = $originalWidth / ($originalHeight / $maxNewHeight); } $newWidth = ceil($newWidth); $newHeight = ceil($newHeight); } else { $newWidth = $originalWidth; $newHeight = $originalHeight; } $ok = FALSE; if (CL::getConf('CL_Images/engine') == 'imagick-cli') { exec("convert -thumbnail " . $newWidth . "x" . $newHeight . " " . $inputFileName . " " . $outputFileName); $ok = TRUE; } elseif (CL::getConf('CL_Images/engine') == 'imagick-php') { $image = new Imagick($inputFileName); $image->thumbnailImage($newWidth, $newHeight); $ok = (bool) $image->writeImage($outputFileName); $image->clear(); $image->destroy(); } else { $out = imageCreateTrueColor($newWidth, $newHeight); switch (strtolower($fileType)) { case 'image/jpeg': $source = imageCreateFromJpeg($inputFileName); break; case 'image/png': $source = imageCreateFromPng($inputFileName); break; case 'image/gif': $source = imageCreateFromGif($inputFileName); break; default: break; } imageCopyResized($out, $source, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight); switch (strtolower($extension)) { case 'jpg': case 'jpeg': if (imageJpeg($out, $outputFileName)) { $ok = TRUE; } break; case 'png': if (imagePng($out, $outputFileName)) { $ok = TRUE; } break; case 'gif': if (imageGif($out, $outputFileName)) { $ok = TRUE; } break; default: break; } imageDestroy($out); imageDestroy($source); } if ($ok and chmod($outputFileName, 0777)) { return TRUE; } else { return FALSE; } }
function fn_makeImage($photographName, $selectionToPhotographRectangle = null, $zoom = 1, $width = null, $height = null, $filepath = null) { $imageSpecs = getimagesize($photographName); $extension = substr($photographName, -4); switch (strtolower($extension)) { case '.jpg': $image = imageCreateFromJpeg($photographName); break; case '.png': $image = imageCreateFrompng($photographName); break; case '.gif': $image = imageCreateFromGif($photographName); break; default: $image = imageCreateFromJpeg($photographName); break; } // try to split bounding box on comma ',' $coordiantesArray = split(",", $selectionToPhotographRectangle); if (!$coordiantesArray[1]) { // try to split on space ' ' $coordiantesArray = split(" ", $selectionToPhotographRectangle); } if (!$coordiantesArray[1]) { // still no split? use whole image $coordiantesArray = array(0, 0, $imageSpecs[0], $imageSpecs[1]); } // translate boundingbox's x1,y1,x2,y2 to x1,y1,w,h $fn_x1 = $coordiantesArray[0]; $fn_y1 = $coordiantesArray[1]; $fn_w = $coordiantesArray[2] - $coordiantesArray[0]; $fn_h = $coordiantesArray[3] - $coordiantesArray[1]; if (!$zoom) { // no zoom? give full size $zoom = 1; } displayDebug("selection: {$selectionToPhotographRectangle}", 3); displayDebug("\n{$fn_x1} | {$fn_y1} | {$fn_w} | {$fn_h} ", 3); // adjust for width and height params if passed if ($width && !$height) { $height = $width * $imageSpecs[1] / $imageSpecs[0]; } else { if (!$width) { $width = $fn_w * $zoom; } if (!$height) { $height = $fn_h * $zoom; } } // let's grabbed the region #$croppedImage=ImageCreate($width, $height); $croppedImage = imagecreatetruecolor($width, $height); imagecopyresized($croppedImage, $image, 0, 0, $coordiantesArray[0], $coordiantesArray[1], $width, $height, $fn_w, $fn_h); $image = $croppedImage; if ($filepath) { // output to file switch (strtolower($extension)) { // send to browser with proper header case '.jpg': imagejpeg($image, $filepath); break; case '.png': imagepng($image, $filepath); break; case '.gif': imageGif($image, $filepath); break; default: imagejpeg($image, $filepath); break; } } else { // output to browser switch (strtolower($extension)) { // send to browser with proper header case '.jpg': header('Content-Type: image/jpeg'); imagejpeg($image); break; case '.png': header('Content-Type: image/png'); imagepng($image); break; case '.gif': header('Content-Type: image/gif'); imageGif($image); break; default: header('Content-Type: image/jpeg'); imagejpeg($image); break; } } // delete image from memory imagedestroy($image); return true; }
/** * @author Matt Squirrell * @source http://php.net/manual/fr/function.imagecreatefromjpeg.php * @licence none * * @param <i>String</i> url de l'image * @return <i>Image</i> copie de l'image */ protected function imageCreateFromAny($filepath) { $type = exif_imagetype($filepath); // [] if you don't have exif you could use getImageSize() $allowedTypes = array(1, 2, 3, 6); if (!in_array($type, $allowedTypes)) { return "error"; } switch ($type) { case 1: $im = imageCreateFromGif($filepath); break; case 2: $im = imageCreateFromJpeg($filepath); break; case 3: $im = imageCreateFromPng($filepath); break; case 6: $im = imageCreateFromBmp($filepath); break; } return $im; }
/** * Rotate an image (left or right) * * @param string $sImage Full path to the image * @param string $sCmd Command to perform. Must be "left" or "right" (without quotes) * @return mixed FALSE on failure, NULL on success */ public function rotate($sImage, $sCmd, $sActualFile = null) { if (!$this->_load($sImage)) { return false; } switch ($this->_aInfo[2]) { case 1: $hFrm = @imageCreateFromGif($this->sPath); break; case 3: $hFrm = @imageCreateFromPng($this->sPath); break; default: $hFrm = @imageCreateFromJpeg($this->sPath); break; } if (substr($this->sPath, 0, 7) != 'http://') { @unlink($this->sPath); } if (function_exists('imagerotate')) { if ($sCmd == 'left') { $im2 = imagerotate($hFrm, 90, 0); } else { $im2 = imagerotate($hFrm, 270, 0); } } else { $wid = imagesx($hFrm); $hei = imagesy($hFrm); $im2 = imagecreatetruecolor($hei, $wid); switch ($this->sType) { case 'jpeg': case 'jpg': case 'jpe': imagealphablending($im2, true); break; case 'png': //imagealphablending($im2, false); //imagesavealpha($im2, true); break; } for ($i = 0; $i < $wid; $i++) { for ($j = 0; $j < $hei; $j++) { $ref = imagecolorat($hFrm, $i, $j); if ($sCmd == 'right') { imagesetpixel($im2, $hei - 1 - $j, $i, $ref); } else { imagesetpixel($im2, $j, $wid - $i, $ref); } } } } switch ($this->sType) { case 'gif': @imagegif($im2, $this->sPath); break; case 'png': imagealphablending($im2, false); imagesavealpha($im2, true); @imagepng($im2, $this->sPath); break; default: @imagejpeg($im2, $this->sPath); break; } imagedestroy($hFrm); imagedestroy($im2); if (Phpfox::getParam('core.allow_cdn')) { Phpfox::getLib('cdn')->put($this->sPath, $sActualFile); } }
/** * Original source: https://stackoverflow.com/questions/12661/efficient-jpeg-image-resizing-in-php * Resize images for thumbnails/mobile * @param str $sourcefile * @param str $endfile * @param int $thumbwidth * @param int $thumbheight * @param int $quality */ public function makeThumbnail($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality) { // Takes the sourcefile (path/to/image.jpg) and makes a thumbnail from it // and places it at endfile (path/to/thumb.jpg). // Load image and get image size. $type = exif_imagetype($sourcefile); // [] if you don't have exif you could use getImageSize() switch ($type) { case 1: $img = imageCreateFromGif($sourcefile); break; case 2: $img = imageCreateFromJpeg($sourcefile); break; case 3: $img = imageCreateFromPng($sourcefile); break; case 6: $img = imageCreateFromBmp($sourcefile); break; } $width = imagesx($img); $height = imagesy($img); // Don't make images larger than the original if ($thumbwidth > $width) { $thumbwidth = $width; } if ($thumbheight > $height) { $thumbheight = $height; } // Resized dimensions $newwidth = $thumbwidth; $divisor = $width / $thumbwidth; $newheight = floor($height / $divisor); // Create a new temporary image. $tmpimg = imagecreatetruecolor($newwidth, $newheight); // Copy and resize old image into new image. imagecopyresampled($tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); // Save thumbnail into a file. $returnVal = imagejpeg($tmpimg, $endfile, $quality); // Release the memory imagedestroy($tmpimg); imagedestroy($img); return $returnVal; }
/** * Compressing a GIF file if not already LZW compressed. * This function is a workaround for the fact that ImageMagick and/or GD does not compress GIF-files to their minimun size (that is RLE or no compression used) * * The function takes a file-reference, $theFile, and saves it again through GD or ImageMagick in order to compress the file * GIF: * If $type is not set, the compression is done with ImageMagick (provided that $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'] is pointing to the path of a lzw-enabled version of 'convert') else with GD (should be RLE-enabled!) * If $type is set to either 'IM' or 'GD' the compression is done with ImageMagick and GD respectively * PNG: * No changes. * * $theFile is expected to be a valid GIF-file! * The function returns a code for the operation. * * @param string $theFile Filepath * @param string $type See description of function * @return string Returns "GD" if GD was used, otherwise "IM" if ImageMagick was used. If nothing done at all, it returns empty string. */ public static function gif_compress($theFile, $type) { $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX']; $returnCode = ''; // GIF... if ($gfxConf['gif_compress'] && strtolower(substr($theFile, -4, 4)) == '.gif') { // IM if (($type == 'IM' || !$type) && $gfxConf['im'] && $gfxConf['im_path_lzw']) { // Use temporary file to prevent problems with read and write lock on same file on network file systems $temporaryName = dirname($theFile) . '/' . md5(uniqid('', TRUE)) . '.gif'; // Rename could fail, if a simultaneous thread is currently working on the same thing if (@rename($theFile, $temporaryName)) { $cmd = self::imageMagickCommand('convert', '"' . $temporaryName . '" "' . $theFile . '"', $gfxConf['im_path_lzw']); \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd); unlink($temporaryName); } $returnCode = 'IM'; if (@is_file($theFile)) { self::fixPermissions($theFile); } } elseif (($type == 'GD' || !$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png']) { // GD $tempImage = imageCreateFromGif($theFile); imageGif($tempImage, $theFile); imageDestroy($tempImage); $returnCode = 'GD'; if (@is_file($theFile)) { self::fixPermissions($theFile); } } } return $returnCode; }
<?php require_once dirname(__FILE__) . '/../../config/config.inc.php'; require_once dirname(__FILE__) . '/../../init.php'; require_once dirname(__FILE__) . '/menu.class.php'; $img = imageCreateFromGif(dirname(__FILE__) . '/gfx/menu/menu_orig.gif'); if (isset($_GET['color']) && strlen($_GET['color']) === 6) { $color = Tools::getValue('color'); $light = -150; if (isset($_GET['light']) && ((int) $_GET['light'] >= 0 && (int) $_GET['light'] <= 200)) { $light = (int) $_GET['light'] + $light; } else { $light += 100; } Menu::colorize($img, $color, $light); } if (isset($_GET['preview'])) { header('Content-type: image/gif'); imageGif($img); } imagedestroy($img);