function imageHandler($sourcefile, $savename, $savedir, $widthmax, $heightmax, $quality, $extension) { $destfile = $savedir . "/" . $savename; if (file_exists($destfile)) { unlink($destfile); } if (file_exists($sourcefile)) { preg_match('/\\.(jpg|png|gif)$/', $sourcefile, $ext); $image = new img($sourcefile, $ext[1]); //echo $widthmax.'/'.$heightmax;exit(); $image->resize($widthmax, $heightmax, true); $image->store($destfile); chmod($destfile, 0777); } }
private function drawImages($dir) { $files = $this->getImages($dir); foreach ($files as $fname) { $out .= '<a href="' . $fname . '">' . '<img width="' . self::THUMB_W . '" src="' . img::updateThumbnail($fname, self::THUMB_W, 0) . '" />' . '</a>'; } return $out; }
static function avatar($picture, $size_data = array(200, 100, 75, 50, 32), $save_dir = '') { $image = img::open($picture); $true_size = img::info($image, 'width'); $save_name = basename($picture, pathinfo($picture, PATHINFO_EXTENSION)); if ($true_size >= $size_data[0]) { $arr = null; foreach ($size_data as $target_size) { $target_img = img::create($target_size, $target_size, 'ffffff', true); $arr = array(0, 0, 0, 0, $target_size, $target_size, $true_size, $true_size); $copy_result = img::copy($target_img, $image, 5, $arr); if ($copy_result) { img::save($target_img, $save_name . '.gif', $save_dir . $target_size . '/'); } } return true; } }
static function avatar($img, $size_data = array(100, 75, 50, 32), $save_dir = '') { $res = img::open($img); $true_size = img::info($res, 'width'); $save_name = basename($img); $save_name = substr($save_name, 0, strpos($save_name, '.')); if ($true_size >= $size_data[0]) { $arr = null; foreach ($size_data as $target_size) { $target_img = img::create($target_size, $target_size, 'ffffff', true); $arr = array(0, 0, 0, 0, $target_size, $target_size, $true_size, $true_size); $copy_res = img::copy($target_img, $res, 5, $arr); if ($copy_res) { img::save($target_img, $save_name . '_' . $target_size . '.gif', $save_dir); } } return true; } }
function do_btn($key, $listing) { list($param, $text) = $listing[$key]; list($fontfile, $fontsize, $alphacolor, $textcolor) = $param; $width = 160; $height = 30; if ($key == 'eude') { $width = $height = 16; } $img = img::Create($width, $height)->FillAlphaHexa($alphacolor); $img->font = $fontfile; $img->SetColorHexa($textcolor); if ($key == 'eude') { $img->Text($text, 0, 8, $fontsize); } else { $img->CenteredText($text, $fontsize); } //-- Fin partie personalisable. ------------------------------------------------ $img->SaveAs(CACHE_PATH . 'btn-' . $key . '.png'); }
$a->change($GLOBALS['PATH_root'] . '../efiles/_thumb/image/' . $filename); unset($a); //echo "$filename - ok<br>"; $aa++; } if (!is_file($GLOBALS['PATH_root'] . '../efiles/image/500/' . $filename)) { $i = new img(250, 250); $i->GenFileInfo($filepath); $i->target = 'save'; $i->change($GLOBALS['PATH_root'] . '../efiles/image/500/' . $filename); unset($i); //echo "$filename - ok<br>"; $ii++; } if (!is_file($GLOBALS['PATH_root'] . '../efiles/image/500/' . $filename)) { $b = new img(500, 500); $b->GenFileInfo($filepath); $b->target = 'save'; $b->change($GLOBALS['PATH_root'] . '../efiles/image/500/' . $filename); unset($b); //echo "$filename - ok<br>"; $bb++; } if ($ii >= $images_limit) { break; } if ($aa >= $images_limit) { break; } if ($bb >= $images_limit) { break;
public function loadThumb() { $this->jsonSend['thumb'] = img::getInstance()->getImage($_POST['id'], false, $_POST['h'], '', 'array'); //pass back the index to the handler $this->jsonSend['index'] = $_POST['index']; $this->sendJson(); }
define('USER', 'root'); define('PASS', ''); define('DBNAME', 'admin_masterapk'); //define('USER','root'); //define('PASS','admin'); //define('DBNAME','2015_etc'); // //require_once( ROOT.'../wp-admin/admin.php' ); include "inc/db.php"; include "inc/lib.php"; include "inc/simple_html_dom.php"; include "inc/function_string.php"; include "inc/resize-class.php"; include "inc/libimg.php"; include "inc/img.php"; $img = new img(); $lib = new lib(); $db = new db(); $catid = (int) $_GET['term_id']; $ar_cat = $lib->ar_cat_string($catid); $total_no_active1 = $lib->get_num_link_no_active($ar_cat); $total_no_active = $total_no_active1; $total_active = $lib->get_num_link_active($ar_cat); $total_link = $total_active + $total_no_active; $phantram = round($total_active * 100 / $total_link, 1); $_SESSION['total'] = $total_link; $_SESSION['da_thuc_hien'] = $total_active; $_SESSION['chua_thuc_hien'] = $total_no_active; $_SESSION['con_lai'] = $total_link - $total_active; $_SESSION['phan_tram'] = $phantram; $data['chua_thuc_hien'] = $total_no_active;
public function __construct() { parent::__construct(); set_time_limit(0); }
public function show($width = false, $height = false, $crop = false, $protocol = null) { if (!$this->is_image()) { return $this->filename(); } if ($width || $height) { $size = $this->versions; if ($width) { $size = $size->where('width', '=', $width); } if ($height) { $size = $size->where('height', '=', $height); } $size = $size->find(); if (!$size->loaded()) { $path = img::get($this->path(), $width, $height, $crop, $this->path); $pathparts = explode('/', $path); $filename = $pathparts[count($pathparts) - 1]; $parentkeyname = $size->parent_key; $size->{$parentkeyname} = $this->id; $size->filename = $filename; $size->width = $width; $size->height = $height; $size->time = time(); $size->save(); } return url::site($this->path . $size->filename, $protocol); } else { return url::site($this->path . $this->filename(), $protocol); } }
static function updateThumbnail($fname, $w, $h, $quality = 25) { $thumbDir = dirname($fname) . '/.thumbs/'; $thumbFname = $thumbDir . basename($fname); $doUpdate = @filectime($fname) > @filectime($thumbFname); if ($doUpdate) { // create thumbs dir if (!file_exists($thumbDir)) { @mkdir($thumbDir); } // save thumbnail $img = new img($fname); $img->resize($w, $h); file_put_contents($thumbFname, $img->render($quality)); } return $thumbFname; }
/** * protected функция загружает логотип * @param (string) $field_name - им поля из формы загрузки файла * @param (string) $upload_dir - директория, в которую загружать файл * @return string (имя картинки) or false (если ф-я вернула false, можно получить ошибки из массива $arrErrors) */ protected function loadLogo($field_name, $upload_dir) { // пробуем загрузить файл if (uploads::uploadImage($field_name, $upload_dir)) { if (img::setParam(uploads::$arrUploadsSubj['file_name'], uploads::$arrUploadsSubj['upload_dir'])) { if (img::createThumbnail(100, 100)) { return true; } else { @unlink(uploads::$arrUploadsSubj['upload_dir'] . uploads::$arrUploadsSubj['file_name']); $this->arrErrors = ERROR_FILE_CREATE_THUMBNAIL; return false; } } else { $this->arrErrors = img::$arrErrors; return false; } } else { // если загрузить файл не удалось, устанавливаем ошибки $this->arrErrors = uploads::$arrErrors; return false; } }
case 'file': default: $files_dir = filesys::setPath(CONF_FILEMANAGER_PATH_TO_FILES); break; } } else { $files_dir = filesys::setPath(CONF_FILEMANAGER_PATH_TO_FILES); } // загружаем файл if ($fm->loadFile('load_file', $files_dir, $fm->arrFileTypes)) { uploads::$fileProperties['path'] = $files_dir; uploads::$fileProperties['link'] = $files_dir; // если файл - изобажение, обрабатываем его if ('image' === $_POST['type']) { if (img::setParam(uploads::$arrUploadsSubj['file_name'], uploads::$arrUploadsSubj['upload_dir'])) { if (img::createThumbnail(CONF_FILEMANAGER_THUMBNAIL_WIDTH, CONF_FILEMANAGER_THUMBNAIL_HEIGHT)) { $dbData = $fm->getFilesProperties($files_dir . 'mda/uploads.mda'); $dbData[uploads::$fileProperties['filename']] = uploads::$fileProperties; $fm->putFilesProperties($files_dir . 'mda/uploads.mda', $dbData); messages::messageChangeSaved(MESSAGE_FILE_LOAD_SUCCESS, false, CONF_ADMIN_FILE . '?m=manager&s=file'); } else { $arrErrors[] = ERROR_FILE_NOT_LOAD; } } else { $arrErrors = img::$arrErrors; } } else { $dbData = $fm->getFilesProperties($files_dir . 'mda/uploads.mda'); $dbData[uploads::$fileProperties['filename']] = uploads::$fileProperties; $fm->putFilesProperties($files_dir . 'mda/uploads.mda', $dbData); messages::messageChangeSaved(MESSAGE_FILE_LOAD_SUCCESS, false, CONF_ADMIN_FILE . '?m=manager&s=file');
public static function getInstance() { return is_object(self::$instance) ? self::$instance : (self::$instance = new self::$instance()); }
} elseif (empty($_FILES[$inputName]['type']) || !empty($_POST['acceptMimeTypes']) && is_array($_POST['acceptMimeTypes']) && !in_array($_FILES[$inputName]['type'], $_POST['acceptMimeTypes'])) { $_FILES[$inputName]['error'] = 'errFileType'; } } // присваиваем файлу уникальное имя $fileName = 'uploads/temporary/' . $_POST['UPLOAD_IDENTIFIER'] . '.' . $_FILES[$inputName]['name']; // если: нет ошибок загрузки файла, перемещаем его в директорию назначения if (empty($_FILES[$inputName]['error'])) { // проверяем существует ли файл с таким именем в папке загрузки if (!file_exists($fileName)) { // перемещаем загруженный файл из временной папки в папку загрузки if (@move_uploaded_file($_FILES[$inputName]['tmp_name'], $fileName)) { // уничтожаем лишние данные (мусор) unset($_FILES[$inputName]['tmp_name'], $_FILES[$inputName]['type'], $_FILES[$inputName]['error']); // обработка загружаемых файлов (опционально по типам) if (!empty($_GET['fType']) && 'rPhotocard' === $_GET['fType'] && (!img::setParam($_POST['UPLOAD_IDENTIFIER'] . '.' . $_FILES[$inputName]['name'], 'uploads/temporary/') || !img::resizeImg(CONF_RESUME_ADD_PHOTO_MAXWIDTH, CONF_RESUME_ADD_PHOTO_MAXHEIGHT, $fileName))) { $_FILES[$inputName]['error'] = 'errFileType'; @unlink($fileName); } } else { $_FILES[$inputName]['error'] = 'errFileUploaded'; // уничтожаем лишние данные (мусор) unset($_FILES[$inputName]['tmp_name']); // уничтожаем временный файл @unlink($_FILES[$inputName]['tmp_name']); } } else { // уничтожаем лишние данные (мусор) unset($_FILES[$inputName]['tmp_name'], $_FILES[$inputName]['type'], $_FILES[$inputName]['error']); } } else {
<?php session_start(); if ($_GET['pic']) { $img = new img('upload/' . $_GET['pic']); $img->resize(); $img->show(); } class img { var $image = ''; var $temp = ''; function img($sourceFile) { if (file_exists($sourceFile)) { $this->image = ImageCreateFromJPEG($sourceFile); } else { $this->errorHandler(); } return; } function resize($width = 400, $height = 400, $aspectradio = true) { $o_wd = imagesx($this->image); $o_ht = imagesy($this->image); if (isset($aspectradio) && $aspectradio) { $w = round($o_wd * $height / $o_ht); $h = round($o_ht * $width / $o_wd); if ($height - $h < $width - $w) { $width =& $w; } else {
/** * Функция устанавливает параметры изображения (использует ф-ю getimagesize) * * @param (string) $imgName - имя файла изображения * @param (string) $imgDir - дарректория, в которой находится файл * * @return bool */ static function setParam($imgName, $imgDir) { $imgDir = filesys::setPath($imgDir); // проверяем существование файла if (@file_exists($imgDir . $imgName)) { // проверяем, является ли файл картинкой if ($params = @getimagesize($imgDir . $imgName)) { // проверяем тип изображения if (in_array($params[2], self::$imgTypes)) { self::$arrImgSubj['name'] = strtolower($imgName); self::$arrImgSubj['dir'] = strtolower($imgDir); self::$arrImgSubj['full_path'] = self::$arrImgSubj['dir'] . self::$arrImgSubj['name']; self::$arrImgSubj['width'] = $params[0]; self::$arrImgSubj['height'] = $params[1]; self::$arrImgSubj['type'] = $params[2]; self::$arrImgSubj['mime'] = strtolower($params['mime']); // если в скприпте установлена настройка "Создавать водяной знак для всех изображений" // т.е. для исходного и для всех его копий // тогда создаем водяной знак. // В этом случае исходное изображение уже будет содержать водяной знак // и все копии этого изображения тоже будут с водяным знаком if (CONF_FILES_IMG_CREATE_WATERMARK && CONF_FILES_IMG_CREATE_WATERMARK_ON === 'all') { if (!img::createWatermark()) { @unlink($imgDir . $imgName); return false; } } switch ($params[2]) { case 1: self::$arrImgSubj['ext'] = 'gif'; self::$arrImgSubj['resource'] = @ImageCreateFromGIF(self::$arrImgSubj['full_path']); break; case 2: self::$arrImgSubj['ext'] = 'jpg'; self::$arrImgSubj['resource'] = @ImageCreateFromJPEG(self::$arrImgSubj['full_path']); break; case 3: self::$arrImgSubj['ext'] = 'png'; self::$arrImgSubj['resource'] = @ImageCreateFromPNG(self::$arrImgSubj['full_path']); break; } // если в скприпте установлена настройка "Создавать водяной знак только для исходного изображения" // тогда создаем водяной знак. // В этом случае водяной знак будет только на одной картинке, а его копии будут без водяного знака if (CONF_FILES_IMG_CREATE_WATERMARK && CONF_FILES_IMG_CREATE_WATERMARK_ON === 'source') { if (!img::createWatermark()) { @unlink($imgDir . $imgName); return false; } } return true; } else { self::setError(ERROR_FILE_FORMAT_ERROR); @unlink($imgDir . $imgName); return false; } } else { self::setError(ERROR_FILE_NOT_IMAGE); @unlink($imgDir . $imgName); return false; } } else { self::setError(ERROR_FILE_NOT_EXISTS); return false; } return false; }
} // IMAGE RESIZE if (preg_match(RESIZE, $request_uri, $i)) { // get image name $filename = DIR_IMG_MAIN . $i[2] . $i[6]; // keep aspect ratio $keep = !empty($i[5]) ? false : true; $image = new img($filename, $i[7]); $image->resize($i[3], $i[4], !empty($i[5]) ? false : true); $image->store(DIR_RESIZED . $i[0]); $image->show(); unset($image); } elseif (preg_match(WATERMARK, $request_uri, $i)) { // get image name $filename = DIR_CUR . 'images' . DIR_SEP . $i[2] . '.jpg'; $image = new img($filename); $image->watermark(DIR_CUR . 'images' . DIR_SEP . 'config' . DIR_SEP . 'watermark.png', 10, 10); $image->store(DIR_WM . $i[0]); $image->show(); unset($image); } elseif (preg_match('/\\/([^\\/]+).html$/i', $request_uri, $i)) { $parsed =& $i[1]; header("HTTP/1.0 200 OK"); require_once DIR_CUR . 'index.php'; } elseif (preg_match('/error.tester$/i', $request_uri)) { header("HTTP/1.0 200 OK"); echo 'ok'; exit; } else { header("HTTP/1.0 404 Not Found"); ?>
public function __construct() { parent::__construct(); }
public static function convertToTrueColor($img) { if (imageistruecolor($img)) { return $img; } $dst = img::createEmptyCanvas(imagesx($img), imagesy($img)); imagecopy($dst, $img, 0, 0, 0, 0, imagesx($img), imagesy($img)); imagedestroy($img); return $dst; }
/** * Process images * @return string */ protected function imageFile($path) { $params = array_intersect_key($_GET, array('x' => '', 'y' => '', 'adapt' => '', 'crop' => '')); $params['path'] = $path; /* Adaptive imgs */ $resMax = 0; if (isset($params['adapt']) && isset($_COOKIE['DW']) && isset($_COOKIE['DH']) && isset($_COOKIE['DPR'])) { $resMax = max($_COOKIE['DW'], $_COOKIE['DH']) * (int) $_COOKIE['DPR']; $resMax = $params['adapt'] = ceil($resMax / 100) * 100; /* to limit amount of cached images versions */ if (isset($params['x']) && $params['x'] > $resMax) { $params['x'] = $resMax; } } $cachePath = 'var/cache/' . str_replace('/', '_', http_build_query($params, '', '_')); /* get only allowed vars and secure generated path */ if (!is_file($cachePath)) { /* if cache doesn't exists */ include 'modules/core/classes/img.php'; $img = new img($path); if (isset($params['x']) && isset($params['y'])) { if (isset($params['crop'])) { $img->crop($params['x'], $params['y']); } else { $img->resize($params['x'], $params['y']); } } elseif ($resMax > 0) { /* If there isn't x and y params we resize img to max Resolution of user's screen */ $img->resize($resMax, 9999); } $img->save($cachePath, 80); } return $cachePath; }
static function edit() { $img_name = post('img_name', 'title'); list($width, $height) = getimagesize($img_name); $p_width = post('p_w', 'int'); $p_height = post('p_h', 'int'); //先缩放 $res = imagecreatetruecolor($p_width, $p_height); $img = img::open($img_name); imagecopyresampled($res, $img, 0, 0, 0, 0, $p_width, $p_height, $width, $height); img::clear($img); //再裁切 $new_img = imagecreatetruecolor(post('n_w', 'int'), post('n_h', 'int')); imagecopyresampled($new_img, $res, 0, 0, post('t_x', 'int'), post('t_y', 'int'), $p_width, $p_height, $p_width, $p_height); $img_name = basename($img_name); img::save($new_img, $img_name, dc_file_create); http::json(array('error' => 0, 'info' => $img_name), true); }
private function batchPhotos() { set_time_limit(0); $msg = '<br><br><br> Cron batch starting with IS_CRON: ' . IS_CRON . ', BATCH_ATTEMPT_LIMIT: ' . BATCH_ATTEMPT_LIMIT . ', BATCH_RESIZE_LIMIT: ' . BATCH_RESIZE_LIMIT . '<br> '; // mail ( '*****@*****.**',$msg, $msg ); $time_start = microtime(true); //start a new array that will probably have a false value for height //if height if false, then we'll use width for resize, and vice versa $resize_dimensions = array(array(GALLERY_THUMB_RESIZE_WIDTH, GALLERY_THUMB_RESIZE_HEIGHT)); //screen hero ratios have HEIGHT sizes in their value slots //eg '800'=>'720','1080'=>'1024': 720 and 1024 are height $ratios = unserialize(SCREEN_HERO_RATIOS); foreach ($ratios as $k => $v) { //the values ($v) in screen_hero_ratios are HEIGHTS //we populate a false for the first slot: WIDTH: thus the heights will be used for this $resize_dimensions[] = array(-1, $v); } //now we probably have an array with false for thumb height, and false for the hero widths //genFuncs::getInstance()->spit ( $resize_dimensions ); $newImages = 0; $existingImages = 0; $ids_were_resized = 0; $ids_attempted = 0; foreach ($this->allImages as $k => $v) { if (($ids_attempted < BATCH_ATTEMPT_LIMIT || BATCH_ATTEMPT_LIMIT == 'all') && $ids_were_resized < BATCH_RESIZE_LIMIT || BATCH_RESIZE_LIMIT == 'all') { $ids_attempted++; //new method: batch_img_limit will iterate over one image id, each id batched to multiple sizes //img object will be responsible for saving each size it creates as a separate db entry in images_resized //there will no longer be an option for img to return a dynamically created image on the live site: way too slow //only pass the id, and an array with a sub-array for each required dimension $id = $v['image_id']; $imageDataResults = img::getInstance()->batchOneImageToAllSizes($id, $resize_dimensions); if ($imageDataResults['did_resize']) { $ids_were_resized++; } } else { //break if you're over the batch limit break; } } $time_end = microtime(true); $execution_time = ($time_end - $time_start) / 60; $exec_t_formatted = number_format($execution_time, 2, '.', ''); //$execution_time $headers = ''; //$headers = "From: " . strip_tags($_POST['req-email']) . "\r\n"; //$headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "\r\n"; //$headers .= "CC: susan@example.com\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; $msg .= '<br><br>--------<br>'; $msg .= 'A CRON job just finished processing.<br><br>'; $msg .= '<b>' . $ids_attempted . ' image ids attempted to be processed.</b><br>'; $msg .= '<b>' . $ids_were_resized . ' ids were resized at least once.</b><br>'; $msg .= '<br>' . $exec_t_formatted . ' minutes to execute.<br>'; $msg .= '<br><br>GD_AVAILABLE ' . GD_AVAILABLE . '<br>'; $msg .= 'IMAGICK_AVAILABLE ' . IMAGICK_AVAILABLE . '<br>'; // if ( ( IS_CRON ) && ( $newImages > 0 ) ) if (IS_CRON) { mail('*****@*****.**', 'Cron batch on Natwalker.com', $msg, $headers); } else { echo $msg; } }
static function transform_image($spath, $dpath, $data) { $datas = explode(':', $data); $srcWidth = $datas[0]; $srcHeight = $datas[1]; $srcX = $datas[2]; $srcY = $datas[3]; $dstWidth = $datas[4]; $dstHeight = $datas[5]; img::load($spath); $origWidth = img::getWidth(); $origHeight = img::getHeight(); $xRatio = $origWidth / $srcWidth; $yRatio = $origHeight / $srcHeight; $srcWidth = $dstWidth * $xRatio; $srcHeight = $dstHeight * $yRatio; $srcX = $srcX * $xRatio; $srcY = $srcY * $yRatio; img::transform($srcX, $srcY, $srcWidth, $srcHeight, $dstWidth, $dstHeight); img::save($dpath); img::unload(); }
if (empty($_GET["tlx"])) { $text_loc_x = 540; } else { $text = htmlspecialchars($_GET["tlx"]); } if (empty($_GET["tly"])) { $text_loc_y = 240; } else { $text = htmlspecialchars($_GET["tly"]); } if (empty($_GET["port"])) { $port = 25565; } else { $port = htmlspecialchars($_GET["port"]); } img::paintImage($ip, $text, $port, $text_loc_x, $text_loc_y); } class img { function paintImage($ip, $text, $port, $text_loc_x, $text_loc_y) { $query = self::QueryMinecraft($ip, $port); if ($query === FALSE) { self::error(); return FALSE; } $motd = $query["HostName"]; $online = '在线人数:' . $query["Players"]; $max = $query["MaxPlayers"]; $ver = $query["Version"]; $im = imagecreatefrompng('background.png');
<?php /** * @author Alex10336 * Dernière modification: $Id$ * @license GNU Public License 3.0 ( http://www.gnu.org/licenses/gpl-3.0.txt ) * @license Creative Commons 3.0 BY-SA ( http://creativecommons.org/licenses/by-sa/3.0/deed.fr ) */ define('IS_IMG', true); define('CHECK_LOGIN', false); include 'init.php'; require_once INCLUDE_PATH . 'Script.php'; require_once CLASS_PATH . 'img.class.php'; include_once INCLUDE_PATH . 'crontab.php'; ignore_user_abort(true); if (IS_IMG) { if ($cron->Run()) { img::Create(3, 3)->SetColorHexa('00FF00')->Fill()->Render(); } else { img::Create(1, 1)->FillAlphaHexa('000000')->Render(); } } else { if (($job = $cron->GetAJob()) !== false) { $job->RunJob(); $cron->Save(); DataEngine::sql_log(); echo get_class($job); } }