示例#1
0
 public function __construct($file)
 {
     // BOF - Zappo - ImagEngine - ONE LINE - Added $file as array, for Text Images
     if (!is_array($file) && file_exists($file)) {
         $this->file = $file;
         $info = getimagesize($file);
         $this->info = array('width' => $info[0], 'height' => $info[1], 'bits' => isset($info['bits']) ? $info['bits'] : '', 'mime' => isset($info['mime']) ? $info['mime'] : '');
         // BOF - Zappo - ImagEngine - Calculate needed Memory, and set memory to that value, so we can do needed calculations
         $memoryNeeded = round(($info[0] * $info[1] * $info['bits'] * 4 / 8 + Pow(2, 16)) * 1.65);
         if (function_exists('memory_get_usage') && memory_get_usage() + $memoryNeeded > (int) ini_get('memory_limit') * pow(1024, 2)) {
             ini_set('memory_limit', (int) ini_get('memory_limit') + ceil((memory_get_usage() + $memoryNeeded - (int) ini_get('memory_limit') * pow(1024, 2)) / pow(1024, 2)) . 'M');
         }
         // EOF - Zappo - ImagEngine - Calculate needed Memory, and set memory to that value, so we can do needed calculations
         $this->image = $this->create($file);
     } else {
         // BOF - Zappo - ImagEngine - If image doesn't exist, create one (for text images 'n stuff)
         $w = is_array($file) ? $file[0] : 5;
         $h = is_array($file) ? $file[1] : 5;
         $this->image = imagecreatetruecolor($w, $h);
         if (is_array($file) && isset($file[2]) && $file[2]) {
             $r = hexdec(substr($file[2], 0, 2));
             $g = hexdec(substr($file[2], 2, 2));
             $b = hexdec(substr($file[2], 4, 2));
             $trans_color = imagecolorallocate($this->image, $r, $g, $b);
         } else {
             imagesavealpha($this->image, true);
             $trans_color = imagecolorallocatealpha($this->image, 0, 0, 0, 127);
         }
         imagefill($this->image, 0, 0, $trans_color);
         $this->info = array('width' => $w, 'height' => $h, 'mime' => 'image/png');
         // EOF - Zappo - ImagEngine - If image doesn't exist, create one (for text images 'n stuff)
     }
 }
示例#2
0
function hasMemoryForImage($serverFilename)
{
    // find out how much total memory this script can access
    $memoryAvailable = return_bytes(@ini_get('memory_limit'));
    // if memory is unlimited, it will return -1 and we don’t need to worry about it
    if ($memoryAvailable == -1) {
        return true;
    }
    // find out how much memory we are already using
    $memoryUsed = memory_get_usage();
    $imgsize = @getimagesize($serverFilename);
    // find out how much memory this image needs for processing, probably only works for jpegs
    // from comments on http://www.php.net/imagecreatefromjpeg
    if (is_array($imgsize) && isset($imgsize['bits']) && isset($imgsize['channels'])) {
        $memoryNeeded = round(($imgsize[0] * $imgsize[1] * $imgsize['bits'] * $imgsize['channels'] / 8 + Pow(2, 16)) * 1.65);
        $memorySpare = $memoryAvailable - $memoryUsed - $memoryNeeded;
        if ($memorySpare > 0) {
            // we have enough memory to load this file
            return true;
        } else {
            // not enough memory to load this file
            $image_info = sprintf('%.2fKB, %d × %d %d bits %d channels', filesize($serverFilename) / 1024, $imgsize[0], $imgsize[1], $imgsize['bits'], $imgsize['channels']);
            Log::addMediaLog('Cannot create thumbnail ' . $serverFilename . ' (' . $image_info . ') memory avail: ' . $memoryAvailable . ' used: ' . $memoryUsed . ' needed: ' . $memoryNeeded . ' spare: ' . $memorySpare);
            return false;
        }
    } else {
        // assume there is enough memory
        // TODO find out how to check memory needs for gif and png
        return true;
    }
}
示例#3
0
文件: image.php 项目: ntamvl/board
function _setMemoryLimitForImage($image_path)
{
    $imageInfo = getimagesize($image_path);
    $imageInfo['channels'] = !empty($imageInfo['channels']) ? $imageInfo['channels'] : 1;
    $imageInfo['bits'] = !empty($imageInfo['bits']) ? $imageInfo['bits'] : 1;
    $memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);
    if (function_exists('memory_get_usage') && memory_get_usage() + $memoryNeeded > (int) ini_get('memory_limit') * pow(1024, 2)) {
        ini_set('memory_limit', (int) ini_get('memory_limit') + ceil((memory_get_usage() + $memoryNeeded - (int) ini_get('memory_limit') * pow(1024, 2)) / pow(1024, 2)) . 'M');
    }
}
 /**
  * Set memory in case of very big images (more than 1Mb)
  * new SmartImage($src, true) to activate this function
  * Works with (PHP 4 >= 4.3.2, PHP 5) if compiled with --enable-memory-limit
  *   or PHP>=5.2.1
  * Thanks to Andrvm and to Bascunan for this feature
  */
 private function setMemoryForBigImage($filename)
 {
     $imageInfo = getimagesize($filename);
     $memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);
     $memoryLimit = (int) ini_get('memory_limit') * 1048576;
     if (memory_get_usage() + $memoryNeeded > $memoryLimit) {
         ini_set('memory_limit', ceil((memory_get_usage() + $memoryNeeded + $memoryLimit) / 1048576) . 'M');
         return true;
     } else {
         return false;
     }
 }
示例#5
0
 /**
  * Get image needed memory size
  *
  * @param string $file
  * @return float|int
  */
 protected function _getImageNeedMemorySize($file)
 {
     $imageInfo = getimagesize($file);
     if (!isset($imageInfo[0]) || !isset($imageInfo[1])) {
         return 0;
     }
     if (!isset($imageInfo['channels'])) {
         // if there is no info about this parameter lets set it for maximum
         $imageInfo['channels'] = 4;
     }
     if (!isset($imageInfo['bits'])) {
         // if there is no info about this parameter lets set it for maximum
         $imageInfo['bits'] = 8;
     }
     return round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);
 }
示例#6
0
 /**
  * Takes memory required to process supplied image file and a bit more for future PHP operations.
  * @param resource $imageFile
  * @return bool true on success
  */
 protected function getMemoryNeeded($imageFile)
 {
     if (!file_exists($imageFile)) {
         return 0;
     }
     $imageInfo = getimagesize($imageFile);
     if (!isset($imageInfo['channels']) || !$imageInfo['channels']) {
         $imageInfo['channels'] = 4;
     }
     if (!isset($imageInfo['bits']) || !$imageInfo['bits']) {
         $imageInfo['bits'] = 8;
     }
     if (!isset($imageInfo[0])) {
         $imageInfo[0] = 1;
     }
     if (!isset($imageInfo[1])) {
         $imageInfo[1] = 1;
     }
     $memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);
     $success = \Ip\Internal\System\Helper\SystemInfo::allocateMemory($memoryNeeded);
     return $success;
 }
示例#7
0
 /**
  * @param string $filename
  * @return resource|string
  */
 private function get_gd_resource($filename)
 {
     $mime = $this->info['mime'];
     //some images processing can run out of original PHP memory limit size
     //Dynamic memory allocation based on K.Tamutis solution on the php manual
     $mem_estimate = round(($this->info['width'] * $this->info['height'] * $this->info['bits'] * $this->info['channels'] / 8 + Pow(2, 16)) * 1.7);
     if (function_exists('memory_get_usage')) {
         if (memory_get_usage() + $mem_estimate > (int) ini_get('memory_limit') * pow(1024, 2)) {
             $new_mem = (int) ini_get('memory_limit') + ceil((memory_get_usage() + $mem_estimate - (int) ini_get('memory_limit') * pow(1024, 2)) / pow(1024, 2)) . 'M';
             //TODO. Validate if memory change was in fact changed or report an error
             ini_set('memory_limit', $new_mem);
         }
     }
     $res_img = '';
     if ($mime == 'image/gif') {
         $res_img = imagecreatefromgif($filename);
     } elseif ($mime == 'image/png') {
         $res_img = imagecreatefrompng($filename);
     } elseif ($mime == 'image/jpeg') {
         $res_img = imagecreatefromjpeg($filename);
     }
     return $res_img;
 }
示例#8
0
 public static function setMemoryForImage($filename)
 {
     $imageInfo = getimagesize($filename);
     $MB = Pow(1024, 2);
     // number of bytes in 1M
     $K64 = Pow(2, 16);
     // number of bytes in 64K
     $TWEAKFACTOR = 1.8;
     // Or whatever works for you
     $memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + $K64) * $TWEAKFACTOR);
     $memoryHave = memory_get_usage();
     $memoryLimitMB = (int) ini_get('memory_limit');
     $memoryLimit = $memoryLimitMB * $MB;
     if (function_exists('memory_get_usage') && $memoryHave + $memoryNeeded > $memoryLimit) {
         $newLimit = $memoryLimitMB + ceil(($memoryHave + $memoryNeeded - $memoryLimit) / $MB);
         ini_set('memory_limit', $newLimit . 'M');
         if ($newLimit > (int) ini_get('memory_limit')) {
             return false;
         } else {
             return true;
         }
     } else {
         return true;
     }
 }
示例#9
0
 /**
  * Calculate and set memory for jpeg
  * Credit to Karolis Tamutis karolis.t_AT_gmail.com
  *
  * @param string $path
  */
 private function _jpegMemoryAllocation($path)
 {
     $memoryNeeded = round(($this->_gdImageData[0] * $this->_gdImageData[1] * $this->_gdImageData['bits'] * $this->_gdImageData['channels'] / 8 + Pow(2, 16)) * 1.65);
     if (function_exists('memory_get_usage') && memory_get_usage() + $memoryNeeded > (int) ini_get('memory_limit') * pow(1024, 2)) {
         ini_set('memory_limit', (int) ini_get('memory_limit') + ceil((memory_get_usage() + $memoryNeeded - (int) ini_get('memory_limit') * pow(1024, 2)) / pow(1024, 2)) . 'M');
     }
 }
 private function setMemory($imageVar)
 {
     $imageInfo = getimagesize($this->{$imageVar});
     $memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);
     if (function_exists('memory_get_usage') && memory_get_usage() + $memoryNeeded > (int) ini_get('memory_limit') * pow(1024, 2)) {
         ini_set('memory_limit', 2 * (int) ini_get('memory_limit') + ceil((memory_get_usage() + $memoryNeeded - (int) ini_get('memory_limit') * pow(1024, 2)) / pow(1024, 2)) . 'M');
     }
 }
示例#11
0
 protected function _getNeedMemoryForFile($file = null)
 {
     $file = is_null($file) ? $this->getBaseFile() : $file;
     if (!$file) {
         return 0;
     }
     if (!file_exists($file) || !is_file($file)) {
         return 0;
     }
     try {
         $imageInfo = getimagesize($file);
     } catch (Exception $e) {
         return 0;
     }
     if (!isset($imageInfo[0]) || !isset($imageInfo[1])) {
         return 0;
     }
     if (!isset($imageInfo['channels'])) {
         // if there is no info about this parameter lets set it for maximum
         $imageInfo['channels'] = 4;
     }
     if (!isset($imageInfo['bits'])) {
         // if there is no info about this parameter lets set it for maximum
         $imageInfo['bits'] = 8;
     }
     return round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);
 }
 /**
  * createThumbnail
  *
  * G�n�re la vignette d'une image en fonction d'une taille donn�e
  *
  * @author Fr�d�ric Mossmann <*****@*****.**>
  * @param string $album Nom de la photo et cl�, s�par�s par '_'
  * @param string $file Nom de l'album et cl�, s�par�s par '_'
  * @param string $ext Extension de la photo (jpg, gif, etc.)
  * @param string $taille Taille de la vignette � cr�er (avec 's' pour un format carr�)
  * @param boolean $force Force la cr�ation de la vignette, m�me si elle existe d�j�
  */
 public function createThumbnail($album, $file, $ext, $taille = "s128", $force = false, $toext = '')
 {
     $memoryLimit = ini_get("memory_limit");
     switch (substr($memoryLimit, -1)) {
         case 'K':
             $memoryLimit = 1024 * (int) substr($memoryLimit, 0, -1);
             break;
         case 'M':
             $memoryLimit = 1024 * 1024 * (int) substr($memoryLimit, 0, -1);
             break;
         case 'G':
             $memoryLimit = 1024 * 1024 * 1024 * (int) substr($memoryLimit, 0, -1);
             break;
     }
     // A faire dans le .htaccess
     // @ini_set( 'memory_limit', '64M' );
     @ini_set('max_execution_time', '120');
     $path2data = realpath("static");
     $pathfolder = $path2data . '/album/' . $album;
     $pathfile = $pathfolder . '/' . $file . '.' . $ext;
     if ($toext != '') {
         // Changement de format
         $savedfile = $pathfolder . '/' . $file . '_' . $taille . '.' . $toext;
         if (file_exists($savedfile) && !$force) {
             return true;
         }
     } else {
         // Conservation du format
         $savedfile = $pathfolder . '/' . $file . '_' . $taille . '.' . $ext;
         if (file_exists($savedfile) && !$force) {
             return true;
         }
     }
     // D�codage de la taille ('s' pour carr�e et nombre de pixels)
     if (ereg("^s([0-9]+)\$", $taille, $regs)) {
         $size = $regs[1];
         $mode = "square";
     } else {
         $size = $taille;
         $mode = "normal";
     }
     // R�cup�ration des infos de l'image (sinon erreur)
     $file_info = getimagesize($pathfile);
     if ($file_info == false) {
         //echo "Erreur : ".$pathfile;
         return false;
     }
     list($width, $height, $type, $attr) = $file_info;
     // SQUARE //
     if ($mode == "square") {
         $square_width = $width;
         $square_height = $height;
         if ($square_width >= $square_height) {
             // Plus large que haut
             $square_y = 0;
             $square_size = $square_height;
             $square_x = round($square_width - $square_height) / 2;
         } else {
             // Plus haut que large
             $square_x = 0;
             $square_size = $square_width;
             $square_y = round($square_height - $square_width) / 2;
         }
         $square_thumbsize = $size;
     }
     $ratio = max($width, $height) / $size;
     // Doit-on r�duite l'image ?
     if ($ratio > 1) {
         $new_width = round($width / $ratio);
         $new_height = round($height / $ratio);
     } else {
         $new_width = $width;
         $new_height = $height;
     }
     // M�moire d�j� utilis�e par PHP et Iconito
     $memoryUsed = memory_get_usage();
     // M�moire pr�vue pour ouvrir le fichier original
     if (!isset($file_info['channels'])) {
         $file_info['channels'] = 4;
     }
     // Normalement 3, mais au pire avec l'AlphaChannel, on prend 4.
     if (!isset($file_info['bits'])) {
         $file_info['bits'] = 8;
     }
     // 8 bits.
     $memoryNeeded = round(($file_info[0] * $file_info[1] * $file_info['bits'] * $file_info['channels'] / 8 + Pow(2, 16)) * 1.65);
     // M�moire pr�vue pour ouvrir la vignette (en pr�voyant un peu large)
     $memoryNeeded += round((1024 * 1024 * 8 * 4 / 8 + Pow(2, 16)) * 1.65);
     // Est-ce qu'il reste assez de m�moire pour allouer l'image originale et la vignette ?
     if ($memoryLimit - ($memoryUsed + $memoryNeeded) < 0) {
         /*
         echo "<li>memoryLimit=".$memoryLimit."</li>";
         echo "<li>memoryUsed=".$memoryUsed."</li>";
         echo "<li>memoryNeeded=".$memoryNeeded."</li>";
         echo "<li>Free=".($memoryLimit-($memoryUsed+$memoryNeeded))."</li>";
         */
         return false;
     }
     // Ouverture du fichier en fonction du format
     switch ($ext) {
         case "gif":
             $image = @imagecreatefromgif($pathfile);
             break;
         case "jpg":
             $image = @imagecreatefromjpeg($pathfile);
             break;
         case "png":
             $image = @imagecreatefrompng($pathfile);
             break;
     }
     // Si l'image n'est pas ouverte (malgr� les tests), errur.
     if (!$image) {
         return false;
         /* Exemple d'image blanche d'erreur.
            $image = imagecreate(200, 30); // Cr�ation d'une image blanche
            $bgc = imagecolorallocate($image, 255, 255, 255);
            $tc  = imagecolorallocate($image, 128, 128, 128);
            imagefilledrectangle($image, 0, 0, 200, 30, $bgc);
            imagestring($image, 1, 10, 10, "Erreur !", $tc);
            */
     }
     // echo "<li>Usage Apres ouverture: ".memory_get_usage()."</li>";
     if ($mode == "square") {
         // Mode carr�...
         $image_p = imagecreatetruecolor($square_thumbsize, $square_thumbsize);
         imagealphablending($image_p, false);
         imagesavealpha($image_p, true);
         // $white = imagecolorallocate($image_p, 255, 255, 255);
         // imagefill($image_p, 0, 0, $white);
         imagecopyresampled($image_p, $image, 0, 0, $square_x, $square_y, $square_thumbsize, $square_thumbsize, $square_size, $square_size);
     } else {
         // Mode standard...
         $image_p = imagecreatetruecolor($new_width, $new_height);
         imagealphablending($image_p, false);
         imagesavealpha($image_p, true);
         // $white = imagecolorallocate($image_p, 255, 255, 255);
         // imagefill($image_p, 0, 0, $white);
         imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
     }
     if ($toext != '') {
         $ext = $toext;
     }
     // Enregistrement de l'image au format souhait�
     switch ($ext) {
         case "gif":
             imagegif($image_p, $savedfile);
             break;
         case "jpg":
             imagejpeg($image_p, $savedfile);
             break;
         case "png":
             imagepng($image_p, $savedfile);
             break;
     }
     if ($image_p) {
         imagedestroy($image_p);
     }
     imagedestroy($image);
     return true;
 }
示例#13
0
function updateItemTable()
{
    global $thumbnailSizes;
    executeQueryForUpdate("\n        ALTER TABLE @item \n        DROP title, DROP picture, DROP keepPrivate,\n        CHANGE `active` `status` INT NOT NULL DEFAULT 1, \n        CHANGE `expirationTime` `expirationTime` DATETIME NOT NULL, \n        CHANGE `creationtime` `creationtime` DATETIME NOT NULL;", __FILE__, __LINE__);
    executeQueryForUpdate("UPDATE @item SET `expirationTime`=0, expEmailSent=0", __FILE__, __LINE__);
    G::load($cats, "SELECT * FROM @category WHERE expiration!=0");
    foreach ($cats as $cat) {
        executeQueryForUpdate("UPDATE @item SET `expirationTime`= NOW() + INTERVAL {$cat->expiration} DAY WHERE cid={$cat->id};", __FILE__, __LINE__);
    }
    CustomField::addCustomColumns("item");
    G::load($items, "SELECT * FROM @item WHERE col_1!=''");
    $create_fg = array("", "ImageCreateFromGIF", "ImageCreateFromJPEG", "ImageCreateFromPNG");
    $save_fg = array("", "ImageGIF", "ImageJPEG", "ImagePNG");
    $extensions = array("", "gif", "jpg", "png");
    $checkBits = array(0, IMG_GIF, IMG_JPG, IMG_PNG);
    $memoryLimit = byteStr2num(ini_get('memory_limit'));
    foreach ($items as $item) {
        $ext = strstr($item->col_1, "jpg") ? "jpg" : (strstr($item->col_1, "gif") ? "gif" : (strstr($item->col_1, "png") ? "png" : ""));
        if (!$ext) {
            continue;
        }
        executeQueryForUpdate("UPDATE @item SET col_1='{$ext}' WHERE id={$item->id}", __FILE__, __LINE__);
        $fname = AD_PIC_DIR . "/{$item->id}.{$ext}";
        if (file_exists($fname)) {
            @unlink(AD_PIC_DIR . "/th_{$item->id}.{$ext}");
            // a regi thumbnailt toroljuk
            copy($fname, AD_PIC_DIR . "/{$item->id}_1.{$ext}");
            // uj nev a full image-nek
            // mas fg-eket kell hivni az image tipusnak megfeleloen:
            $size = getimagesize($fname);
            $width = $size[0];
            $height = $size[1];
            $type = $size[2];
            // az image tipus, 1=>GIF, 2=>JPG, 3=>PNG
            $ext = $extensions[$type];
            $supported = FALSE;
            if (defined("IMG_GIF") && function_exists("ImageTypes")) {
                $supported = isset($checkBits[$type]) && ImageTypes() & $checkBits[$type];
            }
            // ha az adott image tipus supportalva van:
            if ($supported) {
                foreach ($thumbnailSizes as $thSize => $dimensions) {
                    if (function_exists('memory_get_usage') && $memoryLimit && $memoryLimit != -1) {
                        $channels = isset($size['channels']) ? $size['channels'] : 1;
                        // png has no channels
                        $memoryNeeded = Round(($size[0] * $size[1] * $size['bits'] * $channels / 8 + Pow(2, 16)) * 1.65);
                        $usage = memory_get_usage();
                        //FP::log("Current usage: $usage, limit: $memoryLimit, new to allocate: $memoryNeeded, rest after allocate: ". ($memoryLimit-$usage-$memoryNeeded));
                        // skipping if ImageCreate would exceed the memory limit:
                        if ($usage + $memoryNeeded > $memoryLimit) {
                            continue;
                        }
                    }
                    shrinkPicture($newWidth, $newHeight, $dimensions["width"], $dimensions["height"], $fname);
                    $src_im = $create_fg[$type]($fname);
                    $dst_im = ImageCreateTrueColor($newWidth, $newHeight);
                    imagecopyresampled($dst_im, $src_im, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
                    $th_foname = AD_PIC_DIR . "/th_{$thSize}_{$item->id}_1.{$ext}";
                    // pictures/ads/th_medium_2345_5.jpg
                    $save_fg[$type]($dst_im, $th_foname);
                    imagedestroy($src_im);
                }
            }
            @unlink($fname);
            // a full image-et a regi neven toroljuk
        }
    }
    global $gorumuser, $gorumrecognised;
    $gorumrecognised = TRUE;
    $gorumuser->isAdm = 1;
    $c = new AppCategory();
    $c->recalculateAllItemNums(TRUE);
}
示例#14
0
 /**
  * haveEnoughMemory 
  * 
  * Calculates whether the given image can be resized with the current available memory.
  * 
  * @return boolean
  */
 private function haveEnoughMemory()
 {
     $this->memoryAvailable = ini_get('memory_limit');
     $this->memoryAvailable = substr($this->memoryAvailable, 0, -1);
     $this->memoryAvailable = $this->memoryAvailable * 1024 * 1024;
     $size = $this->destination->getImageSize($this->destination->destinationPath . $this->fileName);
     // channels and bits are not present on all images
     if (!isset($size['channels'])) {
         $size['channels'] = 3;
     }
     if (!isset($size['bits'])) {
         $size['bits'] = 8;
     }
     $this->memoryNeeded = Round(($size[0] * $size[1] * $size['bits'] * $size['channels'] / 8 + Pow(2, 16)) * 1.65);
     if ($this->memoryNeeded > $this->memoryAvailable) {
         // Try to delete from server
         $this->destination->deleteFile($this->fileName);
         $this->fcmsError->add(array('message' => T_('Out of Memory Warning'), 'details' => '<p>' . T_('The photo you are trying to upload is quite large and the server might run out of memory if you continue.') . '<small>(' . number_format($this->memoryNeeded) . ' / ' . number_format($this->memoryAvailable) . ')</small></p>'));
         return false;
     }
     return true;
 }
示例#15
0
/**
 * Load an image from a file into memory
 *
 * @param string pathname of image file
 * @param string
 * @return array resource image handle or NULL
 */
function load_image($path, $mimetype)
{
    // yabs> GD library uses shedloads of memory
    // fp> 256M is way too high to sneak this in here. There should be some checks in the systems page to warn against low memory conditions. Also i'm not sure it makes sense to bump memory just for images. If you allow memory you might as well allow it for anything. Anyways, this is too much to be snuk in.
    // @ini_set('memory_limit', '256M'); // artificially inflate memory if we can
    $err = NULL;
    $imh = NULL;
    $function = NULL;
    $image_info = getimagesize($path);
    if (!$image_info || $image_info['mime'] != $mimetype) {
        $FiletypeCache = get_Cache('FiletypeCache');
        $correct_Filetype = $FiletypeCache->get_by_mimetype($image_info['mime']);
        $correct_extension = array_shift($correct_Filetype->get_extensions());
        $path_info = pathinfo($path);
        $wrong_extension = $path_info['extension'];
        $err = '!' . $correct_extension . ' extension mismatch: use .' . $correct_extension . ' instead of .' . $wrong_extension;
    } else {
        $mime_function = array('image/jpeg' => 'imagecreatefromjpeg', 'image/gif' => 'imagecreatefromgif', 'image/png' => 'imagecreatefrompng');
        if (isset($mime_function[$mimetype])) {
            $function = $mime_function[$mimetype];
        } else {
            // Unrecognized mime type
            $err = '!Unsupported format ' . $mimetype . ' (load_image)';
        }
    }
    //pre_dump( $function );
    if ($function) {
        // Call GD built-in function to load image
        // fp> Note: sometimes this GD call will die and there is no real way to recover :/
        load_funcs('tools/model/_system.funcs.php');
        $memory_limit = system_check_memory_limit();
        $curr_mem_usage = memory_get_usage(true);
        // Calculate the aproximative memory size which would be required to create the image resource
        $tweakfactor = 1.8;
        // Or whatever works for you
        $memory_needed = round(($image_info[0] * $image_info[1] * (isset($image_info['bits']) ? $image_info['bits'] : 4) * (isset($image_info['channels']) ? $image_info['channels'] / 8 : 1) + Pow(2, 16)) * $tweakfactor);
        if ($memory_limit - $curr_mem_usage < $memory_needed) {
            // Don't try to load the image into the memory because it would cause 'Allowed memory size exhausted' error
            return array("!Cannot resize too large image", false);
        }
        $imh = $function($path);
    }
    if ($imh === false) {
        trigger_error('load_image failed: ' . $path . ' / ' . $mimetype);
        // DEBUG
        // e.g. "imagecreatefromjpeg(): $FILE is not a valid JPEG file"
        $err = '!load_image failed (no valid image?)';
    }
    if ($err) {
        error_log('load_image failed: ' . substr($err, 1) . ' (' . $path . ' / ' . $mimetype . ')');
    }
    return array($err, $imh);
}
示例#16
0
         $function = "imagegif";
         $create_function = "imagecreatefromgif";
         break;
     case "image/jpeg":
         $function = "imagejpeg";
         $create_function = "imagecreatefromjpeg";
         break;
     case "image/png":
         $function = "imagegif";
         $create_function = "imagecreatefrompng";
         break;
     default:
         throw new Exception("Unknown mime type ('{$mime}')");
 }
 // Check memory
 $memoryNeeded = round(($src_width * $src_height * $info['bits'] * $info['channels'] / 8 + Pow(2, 16)) * 1.65);
 if (function_exists('memory_get_usage') && memory_get_usage() + $memoryNeeded > (int) ini_get('memory_limit') * pow(1024, 2)) {
     $limit = (int) ini_get('memory_limit') + ceil((memory_get_usage() + $memoryNeeded - (int) ini_get('memory_limit') * pow(1024, 2)) / pow(1024, 2));
     $set = ini_set('memory_limit', $limit + 1 . 'M');
 }
 // Load source image
 $img = call_user_func($create_function, $source);
 // Fill
 $red = hexdec(substr(FONT_COLOR, 0, 2));
 $green = hexdec(substr(FONT_COLOR, 2, 2));
 $blue = hexdec(substr(FONT_COLOR, 4, 2));
 $font_color = imagecolorallocate($img, $red, $green, $blue);
 // Set up font
 $font_path = realpath('.');
 putenv('GDFONTPATH=' . $font_path);
 $font_size = $src_height * FONT_SIZE;
示例#17
0
 function checkMemoryLimitForImage($filename)
 {
     $imageInfo = getimagesize($filename);
     $MB = Pow(1024, 2);
     $K64 = Pow(2, 16);
     $TWEAKFACTOR = 1.5;
     if (!isset($imageInfo['channels'])) {
         $imageInfo['channels'] = 3;
     }
     $memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + $K64) * $TWEAKFACTOR);
     $memoryLimitMB = ini_get('memory_limit');
     if ($memoryLimitMB == 0 || $memoryLimitMB == '') {
         $memoryLimitMB = '8MB';
     }
     preg_match_all('/(.*)M/i', $memoryLimitMB, $matches, PREG_SET_ORDER);
     if (!count($matches)) {
         $memoryLimitMB = $memoryLimitMB / 1024 / 1024;
     }
     $memoryLimitMB = (int) $memoryLimitMB;
     $memoryNeeded = (int) $memoryNeeded / $MB;
     if (function_exists('memory_get_usage') && memory_get_usage() / $MB + $memoryNeeded > $memoryLimitMB) {
         return false;
     } else {
         if ($memoryNeeded > $memoryLimitMB) {
             return false;
         }
     }
     return true;
 }
示例#18
0
文件: Image.php 项目: nukeplus/nuke
 /**
  *
  * @return
  */
 public function set_memory_limit()
 {
     $mb = Pow(1024, 2);
     $k64 = Pow(2, 16);
     $tweakfactor = 1.8;
     $memoryNeeded = round(($this->fileinfo['width'] * $this->fileinfo['height'] * $this->fileinfo['bits'] * $this->fileinfo['channels'] / 8 + $k64) * $tweakfactor);
     $disable_functions = (ini_get('disable_functions') != '' and ini_get('disable_functions') != false) ? array_map('trim', preg_split("/[\\s,]+/", ini_get('disable_functions'))) : array();
     if (extension_loaded('suhosin')) {
         $disable_functions = array_merge($disable_functions, array_map('trim', preg_split("/[\\s,]+/", ini_get('suhosin.executor.func.blacklist'))));
     }
     $memoryHave = (function_exists('memory_get_usage') and !in_array('memory_get_usage', $disable_functions)) ? @memory_get_usage() : 0;
     $memoryLimitMB = (int) ini_get('memory_limit');
     $memoryLimit = $memoryLimitMB * $mb;
     if ($memoryHave + $memoryNeeded > $memoryLimit) {
         $newLimit = $memoryLimitMB + ceil(($memoryHave + $memoryNeeded - $memoryLimit) / $mb);
         if (function_exists('memory_limit') and !in_array('memory_limit', $disable_functions)) {
             ini_set('memory_limit', $newLimit . 'M');
         }
     }
 }
示例#19
0
 function Resize($iTWidth, $iTHeight, $bSquare = false)
 {
     if (!is_writable($this->path)) {
         return setError(sprintf(_('Canot resize image %s. File is not writable.'), $this->getPrintedName()));
     }
     $iWidth = $this->getWidth();
     $iHeight = $this->getHeight();
     $iWTBorder = $bSquare ? intval((max($iTWidth, $iTHeight) - $iTWidth) / 2) : 0;
     $iHTBorder = $bSquare ? intval((max($iTWidth, $iTHeight) - $iTHeight) / 2) : 0;
     if (!USE_GD && !is_file(CONVERT_PATH)) {
         return setError(sprintf(_('Can not resize image %s. Imagemagick binary not exists'), $this->getPrintedName()));
     }
     if (!USE_GD) {
         $strBorder = !$bSquare ? '' : '-bordercolor white -border ' . $iWTBorder . 'x' . $iHTBorder;
         $strCommand = CONVERT_PATH . ' -resize ' . $iTWidth . 'x' . $iTHeight . ' ' . $strBorder . ' "' . $this->path . '" "' . $this->path . '"';
         exec($strCommand);
     } else {
         //first check that the image memory limit is ok, else change the memory limit
         $bNeedRestoreMemoryLimit = false;
         $iMB = Pow(1024, 2);
         //number of bytes in 1M
         $iSysMemLimit = intval(ini_get('memory_limit')) * $iMB;
         $iSysNeeded = $this->_getImageMemorySize() + (function_exists('memory_get_usage') ? memory_get_usage() : 0);
         //currentuse
         if ($iSysNeeded > $iSysMemLimit) {
             ini_set('memory_limit', ceil($iSysNeeded / $iMB) . 'M');
             $bNeedRestoreMemoryLimit = true;
             $iSysMemLimit = intval(ini_get('memory_limit')) * $iMB;
             if ($iSysNeeded > $iSysMemLimit) {
                 return setError(sprintf(_('Error in resizing image. Memory Limit is to low. Need %s M of memory.'), ceil($iSysNeeded / $iMB) . ''));
             }
         }
         $strImgExt = strtolower($this->getExtension());
         switch (strtolower($this->getExtension())) {
             case 'png':
                 $oImg = @imagecreatefrompng($this->path);
                 break;
             case 'gif':
                 $oImg = @imagecreatefromgif($this->path);
                 break;
             case 'jpeg':
                 $oImg = @imagecreatefromjpeg($this->path);
                 break;
             case 'jpg':
                 $oImg = @imagecreatefromjpeg($this->path);
                 break;
             default:
                 return setError(sprintf(_('%s images are not supported by gd.'), $strImgExt));
         }
         if (!$oImg) {
             return setError('Can not create image buffer.');
         }
         //first resize the image
         $oImgResizedTmp = imagecreatetruecolor($iTWidth, $iTHeight);
         if ($strImgExt == 'png' && !$bSquare) {
             imagealphablending($oImgResizedTmp, true);
             imagesavealpha($oImgResizedTmp, true);
             $transparent = imagecolorallocatealpha($oImgResizedTmp, 255, 255, 255, 127);
             imagefilledrectangle($oImgResizedTmp, 0, 0, $iTWidth, $iTHeight, $transparent);
         }
         imagecopyresampled($oImgResizedTmp, $oImg, 0, 0, 0, 0, $iTWidth, $iTHeight, $iWidth, $iHeight);
         //need gd2
         imagedestroy($oImg);
         if (!$bSquare) {
             $oImgResized =& $oImgResizedTmp;
         } else {
             //we add border to the image if we want a square
             $oImgResized = imagecreatetruecolor(max($iTWidth, $iTHeight), max($iTWidth, $iTHeight));
             imagefill($oImgResized, 0, 0, ImageColorAllocate($oImgResized, 255, 255, 255));
             //fill background to white
             imagecopy($oImgResized, $oImgResizedTmp, $iWTBorder, $iHTBorder, 0, 0, $iTWidth, $iTHeight);
             imagedestroy($oImgResizedTmp);
         }
         //save image
         if ($strImgExt == "png") {
             imagepng($oImgResized, $this->path, 100);
         }
         if ($strImgExt == "gif") {
             imagegif($oImgResized, $this->path, 100);
         } else {
             imagejpeg($oImgResized, $this->path, 100);
         }
         imagedestroy($oImgResized);
         $bNeedRestoreMemoryLimit && ini_restore('memory_limit');
     }
     /*if(!$bSquare){
     			$iWidth = $this->getWidth();
     			$iHeight = $this->getHeight();
     			if( $iWidth != $iTWidth || $iHeight != $iTHeight )
     				return setError(sprintf(_('An error occured while resizing image %s.'),$this->getPrintedName()));
     		}*/
     return true;
 }
示例#20
0
 function imageUploadExceedsMemory($info)
 {
     $memoryLimit = byteStr2num(ini_get('memory_limit'));
     if (function_exists('memory_get_usage') && $memoryLimit && $memoryLimit != -1) {
         $channels = isset($info['channels']) ? $info['channels'] : 1;
         // png has no channels
         $memoryNeeded = Round(($info[0] * $info[1] * $info['bits'] * $channels / 8 + Pow(2, 16)) * 1.65);
         $usage = memory_get_usage();
         //FP::log("Current usage: $usage, limit: $memoryLimit, new to allocate: $memoryNeeded, rest after allocate: ". ($memoryLimit-$usage-$memoryNeeded));
         // skipping if ImageCreate would exceed the memory limit:
         return $usage + $memoryNeeded > $memoryLimit;
     }
     return FALSE;
 }
 function resize($file, $type, $width, $height)
 {
     global $my, $mainframe, $database, $option, $priTask, $subTask;
     global $WBG_CONFIG, $wbGalleryDB_cat;
     // Debug
     echo "Resizing: " . $file . ' to ' . $width . 'x' . $height . '<br/>';
     // Specify the Minimum Image Size for ImageMagick Processing
     $im_min_limit = 0;
     // Collect the Image Information
     $imgInfo = getimagesize($file);
     printf('Loading image %s, size %s * %s, bpp %s... <br/>', $file, $imgInfo[0], $imgInfo[1], $imgInfo['bits']);
     if (function_exists('image_type_to_mime_type') && function_exists('exif_imagetype')) {
         echo "File Format Confirmed: " . image_type_to_mime_type(exif_imagetype($file)) . " - {$type}<br/>";
     }
     // Handle Memory Management
     if ($WBG_CONFIG->use_memManager) {
         $memoryLimit = ini_get('memory_limit');
         echo 'Memory Limit: ' . $memoryLimit . " <br/>";
         $memoryUsage = $this->mem_get_usage();
         if ($memoryUsage) {
             echo "Memory Usage is {$memoryUsage} <br/>";
             $memoryNeeded = round(($imgInfo[0] * $imgInfo[1] * $imgInfo['bits'] * $imgInfo['channels'] / 8 + Pow(2, 16)) * 1.65) * 2;
             echo "Memory Required is {$memoryNeeded} <br/>";
             if ($memoryUsage + $memoryNeeded > (int) ini_get('memory_limit') * pow(1024, 2)) {
                 $memLimit = (int) ini_get('memory_limit') + ceil(($memoryUsage + $memoryNeeded - (int) ini_get('memory_limit') * pow(1024, 2)) / pow(1024, 2)) . 'M';
                 echo "Set Memory Limit to {$memLimit} <br/>";
                 ini_set('memory_limit', $memLimit);
             }
         } else {
             echo "Memory Usage Information Unavailable... <br>";
         }
     }
     // Use Mogrify (ImageMagick) if JPEG and Available
     if ($WBG_CONFIG->use_ImageMagik && $WBG_CONFIG->path_ImageMagik && $WBG_CONFIG->file_ImageMagik) {
         if (in_array($type, array('image/jpeg', 'image/jpg', 'image/pjpeg'))) {
             // Debug
             echo "Using Image Magik for JPEG Processing... <br/>";
             if ($imgInfo[0] > $im_min_limit || $imgInfo[1] > $im_min_limit) {
                 exec('ls ' . $WBG_CONFIG->path_ImageMagik . ' | grep ' . $WBG_CONFIG->file_ImageMagik, $res);
                 $res = join(' ', $res);
                 if (preg_match('/' . $WBG_CONFIG->file_ImageMagik . '/', $res)) {
                     echo 'Grep Found ' . $WBG_CONFIG->file_ImageMagik . ' in command list<br/>';
                     echo 'Attempting to Process with ImageMagic<br/>';
                     $imCommand = $WBG_CONFIG->path_ImageMagik . $WBG_CONFIG->file_ImageMagik . ' -resize ' . $width . 'x' . $height . ' ' . $file;
                     echo 'Exec: ' . $imCommand . '<br/>';
                     exec($imCommand, $res, $code);
                     if ($code == 0) {
                         return true;
                     } else {
                         echo "Image Magick Failed with Error Code {$code}... Using GD Library <br/>" . join(' ', $res) . "<br/>";
                     }
                 } else {
                     echo "Image Magik Not Found [ {$res} ]... Using GD Library <br/>";
                 }
             } else {
                 echo "Below Image Magik Minium... Using GD Library <br/>";
             }
         } else {
             echo "Using PHP Image Functions <br/>";
         }
     } else {
         echo "Using PHP Image Functions <br/>";
     }
     // Create Memory Map
     $oldImage = null;
     switch ($type) {
         case 'image/jpeg':
         case 'image/jpg':
         case 'image/pjpeg':
             echo "JPEG Detected <br/>";
             if ($this->CanonPowershotS70($file)) {
                 die("This image was made on a Canon Powershot S70");
             }
             if (!$this->checkValidJPEG($file)) {
                 die("This is Not a Valid JPEG");
             }
             $oldImage = @imagecreatefromjpeg($file);
             break;
         case 'image/png':
             echo "PNG Detected <br/>";
             $oldImage = @imagecreatefrompng($file);
             break;
         case 'image/gif':
             echo "GIF Detected <br/>";
             $oldImage = @imagecreatefromgif($file);
             break;
     }
     if (!$oldImage) {
         echo "Failed to create Image Map <br/>";
         return false;
     }
     // Map Created
     echo "Created Image Map - Ready to Convert <br/>";
     $perc_w = $width / $imgInfo[0];
     $perc_h = $height / $imgInfo[1];
     if ($perc_h > $perc_w) {
         $height = round($imgInfo[1] * $perc_w);
     } else {
         $width = round($imgInfo[0] * $perc_h);
     }
     // Debug
     echo 'Converting to ' . $width . 'x' . $height . '<br/>';
     $newImage = imagecreatetruecolor($width, $height);
     imagecopyresampled($newImage, $oldImage, 0, 0, 0, 0, $width, $height, $imgInfo[0], $imgInfo[1]);
     switch ($type) {
         case 'image/jpeg':
         case 'image/jpg':
         case 'image/pjpeg':
             imagejpeg($newImage, $file);
             break;
         case 'image/png':
             imagepng($newImage, $file);
             break;
         case 'image/gif':
             imagegif($newImage, $file);
             break;
     }
     echo "Resizing Complete <br/>";
     imagedestroy($newImage);
     imagedestroy($oldImage);
     return true;
 }
示例#22
0
 /**
  * Get memory needed to perform image manipulations on the file
  *
  * @param string
  * @return int
  */
 protected function _getNeedMemoryForFile($file = null)
 {
     if (!Mage::helper('uaudio_storage')->isEnabled()) {
         return parent::_getNeedMemoryForFile($file);
     }
     $file = is_null($file) ? $this->getBaseFile() : $file;
     if (!$file) {
         return 0;
     }
     if (!$this->_fileExists($file)) {
         return 0;
     }
     if ($this->_getStorageModel()->isInMedia($file)) {
         $metadata = $this->_getStorageModel()->getMetadata($file);
         if (!isset($metadata['width'])) {
             $imageInfo = getimagesize($this->_getFileFromStorage($file));
             $this->_getStorageModel()->updateMetadata($file, ['width' => $imageInfo[0], 'height' => $imageInfo[1]]);
         } else {
             $imageInfo[0] = $metadata['width'];
             $imageInfo[1] = $metadata['height'];
         }
     } else {
         $imageInfo = getimagesize($file);
     }
     if (!isset($imageInfo[0]) || !isset($imageInfo[1])) {
         return 0;
     }
     if (!isset($imageInfo['channels'])) {
         // if there is no info about this parameter lets set it for maximum
         $imageInfo['channels'] = 4;
     }
     if (!isset($imageInfo['bits'])) {
         // if there is no info about this parameter lets set it for maximum
         $imageInfo['bits'] = 8;
     }
     return round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);
 }
示例#23
0
文件: image.php 项目: orhongool/board
     }
     if (!$aspect) {
         $new_image->cropThumbnailImage($width, $height);
     } else {
         $new_image->scaleImage($width, $height, false);
     }
     $new_image->writeImage($writeTo);
 } else {
     $target['width'] = $currentWidth;
     $target['height'] = $currentHeight;
     $target['x'] = $target['y'] = 0;
     $types = array(1 => 'gif', 'jpeg', 'png', 'swf', 'psd', 'wbmp');
     $imageInfo = getimagesize($fullPath);
     $imageInfo['channels'] = !empty($imageInfo['channels']) ? $imageInfo['channels'] : 1;
     $imageInfo['bits'] = !empty($imageInfo['bits']) ? $imageInfo['bits'] : 1;
     $memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);
     if (function_exists('memory_get_usage') && memory_get_usage() + $memoryNeeded > (int) ini_get('memory_limit') * pow(1024, 2)) {
         ini_set('memory_limit', (int) ini_get('memory_limit') + ceil((memory_get_usage() + $memoryNeeded - (int) ini_get('memory_limit') * pow(1024, 2)) / pow(1024, 2)) . 'M');
     }
     $image = call_user_func('imagecreatefrom' . $types[$currentType], $fullPath);
     ini_restore('memory_limit');
     if ($aspect) {
         if ($currentHeight / $height > $currentWidth / $width) {
             $width = ceil($currentWidth / $currentHeight * $height);
         } else {
             $height = ceil($width / ($currentWidth / $currentHeight));
         }
     } else {
         $proportion_X = $currentWidth / $width;
         $proportion_Y = $currentHeight / $height;
         if ($proportion_X > $proportion_Y) {
示例#24
0
 /**
  * haveEnoughMemory 
  * 
  * Calculates whether the given image can be resized with the current available memory.
  * 
  * @return boolean
  */
 function haveEnoughMemory()
 {
     $this->memoryAvailable = ini_get('memory_limit');
     $this->memoryAvailable = substr($this->memoryAvailable, 0, -1);
     $this->memoryAvailable = $this->memoryAvailable * 1024 * 1024;
     $size = GetImageSize($this->destination . $this->name);
     // channels and bits are not present on all images
     if (!isset($size['channels'])) {
         $size['channels'] = 3;
     }
     if (!isset($size['bits'])) {
         $size['bits'] = 8;
     }
     $this->memoryNeeded = Round(($size[0] * $size[1] * $size['bits'] * $size['channels'] / 8 + Pow(2, 16)) * 1.65);
     if ($this->memoryNeeded > $this->memoryAvailable) {
         $this->error = 4;
         return false;
     }
     return true;
 }
示例#25
0
 /**
  * image::set_memory_limit()
  * 
  * @return
  */
 function set_memory_limit()
 {
     $mb = Pow(1024, 2);
     $k64 = Pow(2, 16);
     $tweakfactor = 1.8;
     $memoryNeeded = round(($this->fileinfo['width'] * $this->fileinfo['height'] * $this->fileinfo['bits'] * $this->fileinfo['channels'] / 8 + $k64) * $tweakfactor);
     $memoryHave = @memory_get_usage();
     $memoryLimitMB = (int) ini_get('memory_limit');
     $memoryLimit = $memoryLimitMB * $mb;
     if ($memoryHave + $memoryNeeded > $memoryLimit) {
         $newLimit = $memoryLimitMB + ceil(($memoryHave + $memoryNeeded - $memoryLimit) / $mb);
         $disable_functions = (ini_get("disable_functions") != "" and ini_get("disable_functions") != false) ? array_map('trim', preg_split("/[\\s,]+/", ini_get("disable_functions"))) : array();
         if (function_exists('memory_limit') and !in_array('memory_limit', $disable_functions)) {
             ini_set('memory_limit', $newLimit . 'M');
         }
     }
 }
示例#26
0
 /**
  * @access private
  */
 function getMemmoryNeeded($image_info)
 {
     if (!isset($image_info['channels']) || !$image_info['channels']) {
         $image_info['channels'] = 4;
     }
     if (!isset($image_info['bits']) || !$image_info['bits']) {
         $image_info['bits'] = 8;
     }
     $memoryNeeded = round(($image_info[0] * $image_info[1] * $image_info['bits'] * $image_info['channels'] / 8 + Pow(2, 16)) * 1.65);
     if (function_exists('memory_get_usage') && memory_get_usage() + $memoryNeeded > (int) ini_get('memory_limit') * pow(1024, 2)) {
         $success = ini_set('memory_limit', (int) ini_get('memory_limit') + 10 + ceil((memory_get_usage() + $memoryNeeded - (int) ini_get('memory_limit') * pow(1024, 2)) / pow(1024, 2)) . 'M');
     } else {
         $success = true;
     }
     return $success;
 }
示例#27
0
 /**
  * @param string|null $file
  * @return float|int
  */
 protected function _getNeedMemoryForFile($file = null)
 {
     $file = is_null($file) ? $this->getBaseFile() : $file;
     if (!$file) {
         return 0;
     }
     if (!$this->_mediaDirectory->isExist($file)) {
         return 0;
     }
     $imageInfo = getimagesize($this->_mediaDirectory->getAbsolutePath($file));
     if (!isset($imageInfo[0]) || !isset($imageInfo[1])) {
         return 0;
     }
     if (!isset($imageInfo['channels'])) {
         // if there is no info about this parameter lets set it for maximum
         $imageInfo['channels'] = 4;
     }
     if (!isset($imageInfo['bits'])) {
         // if there is no info about this parameter lets set it for maximum
         $imageInfo['bits'] = 8;
     }
     return round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);
 }
示例#28
0
 /**
  * creates new thumbnails
  *
  * @access public
  * @param string path with trailing separator
  * @param string path with trailing separator
  * @param array file names and captions
  * @param boolean overwrite existing thumbnails (only relevant for rebuild)
  * @return integer number of thumbnails created or zero on error
  */
 function makeThumbs($thumbPath, $imagePath, $imageData, $overwrite = true)
 {
     $thumbCount = 0;
     $memoryLimit = ini_get('memory_limit') == '' ? MEMORY_LIMIT_FALLBACK : ini_get('memory_limit');
     $maxImageBytes = MEMORY_LIMIT == 0 ? $this->getBytes($memoryLimit) : MEMORY_LIMIT * pow(2, 20);
     $thumbDir = rtrim($thumbPath, '\\/');
     if (!is_dir($thumbDir)) {
         if (@(!mkdir($thumbDir))) {
             trigger_error('the thumbnail directory ' . $thumbDir . ' cannot be created, check parent folder permissions', E_USER_WARNING);
             return 0;
         }
         if (@(!chmod($thumbDir, THUMB_DIR_MODE))) {
             trigger_error('Unable to set permissions for ' . $thumbDir, E_USER_NOTICE);
             return 0;
         }
     }
     $gdVersion = $this->getGDversion();
     if (version_compare($gdVersion, '2.0', '<')) {
         trigger_error('the GD imaging library was not found on this server or it is an old version that does not support jpeg images. Thumbnails will not be created. Either upgrade to a later version of GD or create the thumbnails yourself in a graphics application such as Photoshop.', E_USER_WARNING);
         return 0;
     }
     foreach ($imageData as $key => $imageArray) {
         $fileName = $imageArray['fileName'];
         $image = $imagePath . $fileName;
         $thumb = $thumbPath . $fileName;
         if (@file_exists($thumb) && !$overwrite) {
             continue;
         }
         if (@(!file_exists($image))) {
             trigger_error('image ' . $image . ' cannot be found', E_USER_WARNING);
             continue;
         }
         $imageInfo = GetImageSize($image);
         // $imageInfo['channels'] is not set for png images so just guess at 3
         $channels = 3;
         $memoryNeeded = Round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $channels / 8 + Pow(2, 16)) * MEMORY_SAFETY_FACTOR);
         if ($memoryNeeded > $maxImageBytes) {
             trigger_error('image ' . $image . ' is too large to create a thumbnail', E_USER_WARNING);
             continue;
         }
         if ($this->createThumb($image, $thumb)) {
             $thumbCount++;
         } else {
             trigger_error('Thumbnail for ' . $fileName . ' could not be created', E_USER_WARNING);
         }
     }
     return $thumbCount;
 }
示例#29
0
 /**
  * resizeImage
  *
  * @param string $path,
  * @param string $resWidth
  * @param string $resHeight
  * @param string $saveTo default value null
  *
  * @return void
  */
 public function resizeImage($path, $resWidth, $resHeight, $saveTo = null)
 {
     $imageInfo = @getimagesize($path);
     if (!$imageInfo) {
         throw new Exception("Could not get image information");
     }
     list($width, $height) = $imageInfo;
     $percentHeight = $resHeight / $height;
     $percentWidth = $resWidth / $width;
     $percent = $percentWidth < $percentHeight ? $percentWidth : $percentHeight;
     $resWidth = $width * $percent;
     $resHeight = $height * $percent;
     // Resample
     $image_p = imagecreatetruecolor($resWidth, $resHeight);
     imagealphablending($image_p, false);
     imagesavealpha($image_p, true);
     $background = imagecolorallocate($image_p, 0, 0, 0);
     ImageColorTransparent($image_p, $background);
     // make the new temp image all transparent
     //Assume 3 channels if we can't find that information
     if (!array_key_exists("channels", $imageInfo)) {
         $imageInfo["channels"] = 3;
     }
     $memoryNeeded = Round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] + Pow(2, 16)) * 1.95) / (1024 * 1024);
     if ($memoryNeeded < 80) {
         $memoryNeeded = 80;
     }
     ini_set('memory_limit', intval($memoryNeeded) . 'M');
     $functions = array(IMAGETYPE_GIF => array('imagecreatefromgif', 'imagegif'), IMAGETYPE_JPEG => array('imagecreatefromjpeg', 'imagejpeg'), IMAGETYPE_PNG => array('imagecreatefrompng', 'imagepng'));
     if (!array_key_exists($imageInfo[2], $functions)) {
         throw new Exception("Image format not supported");
     }
     list($inputFn, $outputFn) = $functions[$imageInfo[2]];
     $image = $inputFn($path);
     imagecopyresampled($image_p, $image, 0, 0, 0, 0, $resWidth, $resHeight, $width, $height);
     $outputFn($image_p, $saveTo);
     if (!is_null($saveTo)) {
         G::LoadSystem('inputfilter');
         $filter = new InputFilter();
         $saveTo = $filter->validateInput($saveTo, "path");
     }
     @chmod($saveTo, 0666);
 }
示例#30
0
<?php

namespace {
    $x = pow(1, 2);
    $y = \Pow(POW(3, 4), 5);
}
namespace a {
    // no redefinition
    $xa = pOw(6, 7);
    $ya = \POw(pOW(8, 9), 10);
}
namespace b {
    // with redefinition
    function pow($a, $b)
    {
        print __FUNCTION__ . " {$a} \n";
    }
    $xa = pow(11, 12);
    $ya = \POW(pOw(13, 14), 15);
}