function imageDualResize($filename, $cleanFilename, $wtarget, $htarget) { if (!file_exists($cleanFilename)) { $dims = getimagesize($filename); $width = $dims[0]; $height = $dims[1]; while ($width > $wtarget || $height > $htarget) { if ($width > $wtarget) { $percentage = $wtarget / $width; } if ($height > $htarget) { $percentage = $htarget / $height; } /*if($width > $height) { $percentage = ($target / $width); } else { $percentage = ($target / $height); }*/ //gets the new value and applies the percentage, then rounds the value $width = round($width * $percentage); $height = round($height * $percentage); } $image = new SimpleImage(); $image->load($filename); $image->resize($width, $height); $image->save($cleanFilename); $image = null; } //returns the new sizes in html image tag format...this is so you can plug this function inside an image tag and just get the return "src=\"{$baseurl}/{$cleanFilename}\""; }
function uploadArquivo($campoFormulario, $idGravado) { $ext = pathinfo($_FILES[$campoFormulario][name], PATHINFO_EXTENSION); if (($_FILES[$campoFormulario][name] <> "") && ($_FILES[$campoFormulario][size]) > 0 && in_array(strtolower($ext), $this->extensions)) { $arquivoTmp = $_FILES[$campoFormulario]['tmp_name']; $nome = str_replace(".", "", microtime(true)) . "_" . $_FILES[$campoFormulario]['name']; if (function_exists("exif_imagetype")) { $test = exif_imagetype($arquivoTmp); $image_type = $test; } else { $test = getimagesize($arquivoTmp); $image_type = $test[2]; } if (in_array($image_type, array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP))) { $image = new SimpleImage(); $image->load($arquivoTmp); $l = $image->getWidth(); $h = $image->getHeight(); if ($l > $h) { $funcao = "resizeToWidth"; $novoTamanho = 1024; } else { $funcao = "resizeToHeight"; $novoTamanho = 768; } $image->$funcao($novoTamanho); $copiou = $image->save($this->diretorio . $nome); if ($this->prefixoMarcaDagua) { $image->$funcao(300); $image->watermark(); $image->save($this->diretorio . $this->prefixoMarcaDagua . $nome); } if ($this->prefixoMiniatura) { $image->load($arquivoTmp); $image->$funcao(380); $image->save($this->diretorio . $this->prefixoMiniatura . $nome); } } else { $copiou = copy($arquivoTmp, $this->diretorio . $nome); } if ($copiou) { $sql = "update $this->tabela set $this->campoBD = '$nome' where id='$idGravado'"; #$altualizaNome = mysql_query($sql) or die($sql . mysql_error); $this->conexao->executeQuery($sql); } } else { return false; } return $idGravado; }
function imageProcess($img_info) { $file = $img_info['img_upload_url_temp'] . $img_info['img']; $sizeInfo = getimagesize($file); if (is_array($sizeInfo)) { include_once 'libraries/SimpleImage.php'; $image = new SimpleImage(); $image->load($file); $width = $sizeInfo[0]; $height = $sizeInfo[1]; //img thumb $img_thumb = $img_info['img_upload_url_thumb'] . $img_info['img']; if ($width <= IMAGE_THUMB_WIDTH && $height <= IMAGE_THUMB_HEIGHT) { copy($file, $img_thumb); } elseif ($width >= $height) { $image->resizeToWidth(IMAGE_THUMB_WIDTH); $image->save($img_thumb); } elseif ($width < $height) { $image->resizeToHeight(IMAGE_THUMB_HEIGHT); $image->save($img_thumb); } //img $img = $img_info['img_upload_url'] . $img_info['img']; if ($img_info['original'] == 1) { $image->load($file); if ($width >= $height && $width > IMAGE_MAX_WIDTH) { $image->resizeToWidth(IMAGE_MAX_WIDTH); $image->save($img); } elseif ($width <= $height && $height > IMAGE_MAX_HEIGHT) { $image->resizeToHeight(IMAGE_MAX_HEIGHT); $image->save($img); } else { copy($file, $img); } if (file_exists($file)) { unlink($file); } } else { if (copy($file, $img)) { if (file_exists($file)) { unlink($file); } } } return true; } else { return false; } }
function upload_imagem_unica($pasta_upload, $novo_tamanho_imagem, $novo_tamanho_imagem_miniatura, $host_retorno, $upload_miniatura) { // data atual $data_atual = data_atual(); // array com fotos $fotos = $_FILES['foto']; // extensoes de imagens disponiveis $extensoes_disponiveis[] = ".jpeg"; $extensoes_disponiveis[] = ".jpg"; $extensoes_disponiveis[] = ".png"; $extensoes_disponiveis[] = ".gif"; $extensoes_disponiveis[] = ".bmp"; // nome imagem $nome_imagem = $fotos['tmp_name']; $nome_imagem_real = $fotos['name']; // dimensoes da imagem $image_info = getimagesize($_FILES["foto"]["tmp_name"]); $largura_imagem = $image_info[0]; $altura_imagem = $image_info[1]; // extencao $extensao_imagem = "." . strtolower(pathinfo($nome_imagem_real, PATHINFO_EXTENSION)); // nome final de imagem $nome_imagem_final = md5($nome_imagem_real . $data_atual) . $extensao_imagem; $nome_imagem_final_miniatura = md5($nome_imagem_real . $data_atual . $data_atual) . $extensao_imagem; // endereco final de imagem $endereco_final_salvar_imagem = $pasta_upload . $nome_imagem_final; $endereco_final_salvar_imagem_miniatura = $pasta_upload . $nome_imagem_final_miniatura; // informa se a extensao de imagem e permitida $extensao_permitida = retorne_elemento_array_existe($extensoes_disponiveis, $extensao_imagem); // se nome for valido entao faz upload if ($nome_imagem != null and $nome_imagem_real != null and $extensao_permitida == true) { // upload de imagem normal $image = new SimpleImage(); $image->load($nome_imagem); // aplica escala if ($largura_imagem > $novo_tamanho_imagem) { $image->resizeToWidth($novo_tamanho_imagem); } // salva a imagem grande $image->save($endereco_final_salvar_imagem); // upload de miniatura if ($upload_miniatura == true) { $image = new SimpleImage(); $image->load($nome_imagem); // modo de redimencionar if ($largura_imagem > $novo_tamanho_imagem_miniatura) { $image->resizeToWidth($novo_tamanho_imagem_miniatura); } // salva a imagem em miniatura $image->save($endereco_final_salvar_imagem_miniatura); } // array de retorno $retorno['normal'] = $host_retorno . $nome_imagem_final; $retorno['miniatura'] = $host_retorno . $nome_imagem_final_miniatura; $retorno['normal_root'] = $endereco_final_salvar_imagem; $retorno['miniatura_root'] = $endereco_final_salvar_imagem_miniatura; // retorno return $retorno; } }
function resizeImagesInFolder($dir, $i) { if (!is_dir('cover/' . $dir)) { toFolder('cover/' . $dir); } $files = scandir($dir); foreach ($files as $key => $file) { if ($file != '.' && $file != '..') { if (!is_dir($dir . '/' . $file)) { echo $dir . '/' . $file; $image = new SimpleImage(); $image->load($dir . '/' . $file); if ($image->getHeight() < $image->getWidth()) { $image->resizeToWidth(1920); } else { $image->resizeToHeight(1920); } // $new = 'cover/' . $dir . '/'.$image->name; if ($i < 10) { $new = 'cover/' . $dir . '/00' . $i . '.' . $image->type; } elseif ($i < 100) { $new = 'cover/' . $dir . '/0' . $i . '.' . $image->type; } else { $new = 'cover/' . $dir . '/' . $i . '.' . $image->type; } $image->save($new); echo ' ---------> ' . $new . '<br>'; $i++; } else { resizeImagesInFolder($dir . '/' . $file, 1); } } } }
public function action_index() { $tags = array(); $imager = new SimpleImage(); if ($this->request->param('path')) { // Берем новость $post = ORM::factory('blog')->where('url', '=', $this->request->param('path'))->find(); } else { $post = ORM::factory('blog'); } if ($_POST) { $post_name = Arr::get($_POST, 'post_name'); $post_url = Arr::get($_POST, 'post_url'); $short_text = Arr::get($_POST, 'short_text'); $full_text = Arr::get($_POST, 'full_text'); $tag = Arr::get($_POST, 'tag'); // Загрузка изображения $image = $_FILES["imgupload"]["name"]; if (!empty($image)) { $imager = new SimpleImage(); //$this->news->deleteImage($post->id); //$image = $this->image->upload_image($image['tmp_name'], $image['name'], $this->config->news_images_dir."big/"); move_uploaded_file($_FILES["imgupload"]["tmp_name"], "files/blog/" . $_FILES["imgupload"]["name"]); $imager->load("files/blog/" . $image); $imager->resize(200, 200); $imager->save("files/blog/miniatures/" . $image); } $post->set('name', $post_name)->set('url', $post_url)->set('date', DB::expr('now()'))->set('short_text', $short_text)->set('full_text', $full_text)->set('image', $image)->set('tag_id', ORM::factory('tags')->where('name', '=', $tag)->find())->save(); } $tags = ORM::factory('tags')->find_all(); $content = View::factory('/admin/post')->bind('tags', $tags)->bind('post', $post); $this->template->content = $content; }
protected function uploadFile() { if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $this->path)) { $path = $this->path; if (!$this->db->query("INSERT photo (name,folder,time,status) \n\t\t\tVALUES ('" . $this->name . "','" . $this->folder . "','" . time() . "','temp')")) { die("error"); } $id = $this->db->getLastId(); $this->image->load($path); $full = new SimpleImage(); $full->load($path); if ($full->getWidth() > 1200) { $full->resizeToWidth(1200); } $full->save(str_replace('.', '.full.', $path)); if ($this->image->getWidth() > 600) { $this->image->resizeToWidth(600); } $this->image->save($path); $size = $this->f->getFullSize($path, 90, 90); $img = array('name' => $this->name, 'path' => $path, 'count' => $this->getNum(), 'width' => $size['width'], 'height' => $size['height'], 'id' => $id); echo json_encode($img); } else { echo "error"; } }
/** * 上传图片 */ public function actionUpload() { $fn = $_GET['CKEditorFuncNum']; $url = WaveCommon::getCompleteUrl(); $imgTypeArr = WaveCommon::getImageTypes(); if (!in_array($_FILES['upload']['type'], $imgTypeArr)) { echo '<script type="text/javascript"> window.parent.CKEDITOR.tools.callFunction("' . $fn . '","","图片格式错误!"); </script>'; } else { $projectPath = Wave::app()->projectPath; $uploadPath = $projectPath . 'data/uploadfile/substance'; if (!is_dir($uploadPath)) { mkdir($uploadPath, 0777); } $ym = WaveCommon::getYearMonth(); $uploadPath .= '/' . $ym; if (!is_dir($uploadPath)) { mkdir($uploadPath, 0777); } $imgType = strtolower(substr(strrchr($_FILES['upload']['name'], '.'), 1)); $imageName = time() . '_' . rand() . '.' . $imgType; $file_abso = $url . '/data/uploadfile/substance/' . $ym . '/' . $imageName; $SimpleImage = new SimpleImage(); $SimpleImage->load($_FILES['upload']['tmp_name']); $SimpleImage->resizeToWidth(800); $SimpleImage->save($uploadPath . '/' . $imageName); echo '<script type="text/javascript"> window.parent.CKEDITOR.tools.callFunction("' . $fn . '","' . $file_abso . '","上传成功"); </script>'; } }
function processScreenshots($gameID) { ## Select all fanart rows for the requested game id $ssResult = mysql_query(" SELECT filename FROM banners WHERE keyvalue = {$gameID} AND keytype = 'screenshot' ORDER BY filename ASC "); ## Process each fanart row incrementally while ($ssRow = mysql_fetch_assoc($ssResult)) { ## Construct file names $ssOriginal = $ssRow['filename']; $ssThumb = "screenshots/thumb" . str_replace("screenshots", "", $ssRow['filename']); ## Check to see if the original fanart file actually exists before attempting to process if (file_exists("../banners/{$ssOriginal}")) { ## Check if thumb already exists if (!file_exists("../banners/{$ssThumb}")) { ## If thumb is non-existant then create it $image = new SimpleImage(); $image->load("../banners/{$ssOriginal}"); $image->resizeToWidth(300); $image->save("../banners/{$ssThumb}"); //makeFanartThumb("../banners/$ssOriginal", "../banners/$ssThumb"); } ## Get Fanart Image Dimensions list($image_width, $image_height, $image_type, $image_attr) = getimagesize("../banners/{$ssOriginal}"); $ssWidth = $image_width; $ssHeight = $image_height; ## Output Fanart XML Branch print "<screenshot>\n"; print "<original width=\"{$ssWidth}\" height=\"{$ssHeight}\">{$ssOriginal}</original>\n"; print "<thumb>{$ssThumb}</thumb>\n"; print "</screenshot>\n"; } } }
/** * Generates the thumbnail for a given file. */ protected function _generateThumbnail() { $image = new SimpleImage(); $image->load($this->source); $image->resizeToWidth(Configure::read('Image.width')); $image->save($this->thumb_path); }
function insertImageSub($file, $sub_id, $menu_id) { $error = false; $arr = explode('.', $file["name"]); $imageFileType = end($arr); if ($file["size"] > 5000000) { $error = true; } if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") { $error = true; } if (!$error) { $target_dir = "../images/menu_" . $menu_id . "/sub_" . $sub_id . "/"; $target_file = $target_dir . $file["name"]; // if (!file_exists($target_dir)) { mkdir($target_dir, 0777, true); } if (file_exists($target_file)) { unlink($target_file); } if (move_uploaded_file($file["tmp_name"], $target_file)) { include 'classSimpleImage.php'; $image = new SimpleImage(); $image->load($target_file); $image->resize(218, 138); $image->save($target_file); $arr = explode("../", $target_file); return end($arr); } } else { return false; } }
function ImageResize($file) { $image = new SimpleImage(); $image->load('traffic-images/temp/' . $file); $image->resize(300, 200); $image->save('traffic-images/' . $file); unlink("traffic-images/temp/" . $file); }
public function Load($pathToImage) { if (!extension_loaded('gd')) { die('gd extension is required for image upload'); } $image = new SimpleImage(); $image->load($pathToImage); return new Image($image); }
public function saveImageInFile($file) { $t = $file['tmp_name']; $n = $file['name']; $path = App::get("uploads_dir_original") . DIRECTORY_SEPARATOR . $n; move_uploaded_file($t, $path); $image = new SimpleImage(); $image->load($path); $image->resize(250, 250); $image->save(App::get("uploads_dir_small") . DIRECTORY_SEPARATOR . $n); return $n; }
function upload() { if (!isset($_FILES['upload'])) { $this->directrender('S3/S3'); return; } global $params; // Params to vars $client_id = '1b5cc674ae2f335'; // Validations $this->startValidations(); $this->validate($_FILES['upload']['error'] === 0, $err, 'upload error'); $this->validate($_FILES['upload']['size'] <= 10 * 1024 * 1024, $err, 'size too large'); // Code if ($this->isValid()) { $fname = $_FILES['upload']['tmp_name']; require_once $GLOBALS['dirpre'] . 'includes/S3/SimpleImage.php'; $image = new SimpleImage(); $this->validate($image->load($fname), $err, 'invalid image type'); if ($this->isValid()) { if ($image->getHeight() > 1000) { $image->resizeToHeight(1000); } $image->save($fname); function getMIME($fname) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $mime = finfo_file($finfo, $fname); finfo_close($finfo); return $mime; } $filetype = explode('/', getMIME($fname)); $valid_formats = array("jpg", "png", "gif", "jpeg"); $this->validate($filetype[0] === 'image' and in_array($filetype[1], $valid_formats), $err, 'invalid image type'); if ($this->isValid()) { require_once $GLOBALS['dirpre'] . 'includes/S3/s3_config.php'; //Rename image name. $actual_image_name = time() . "." . $filetype[1]; $this->validate($s3->putObjectFile($fname, $bucket, $actual_image_name, S3::ACL_PUBLIC_READ), $err, 'upload failed'); if ($this->isValid()) { $reply = "https://{$bucket}.s3.amazonaws.com/{$actual_image_name}"; $this->success('image successfully uploaded'); $this->directrender('S3/S3', array('reply' => "up(\"{$reply}\");")); return; } } } } $this->error($err); $this->directrender('S3/S3'); }
static function Thumbnail($image_file, $thumb_file, $width = 48, $height = 48) { $ctype = FSS_Helper::datei_mime("png"); // thumb file exists if (file_exists($thumb_file) && filesize($thumb_file) > 0) { header("Content-Type: " . $ctype); header('Cache-control: max-age=' . 60 * 60 * 24 * 365); header('Expires: ' . gmdate(DATE_RFC1123, time() + 60 * 60 * 24 * 365)); @readfile($thumb_file); exit; } require_once JPATH_SITE . DS . 'components' . DS . 'com_fss' . DS . 'helper' . DS . 'third' . DS . 'simpleimage.php'; $im = new SimpleImage(); $im->load($image_file); if (!$im->image) { // return a blank thumbnail of some sort! $im->load(JPATH_SITE . DS . 'components' . DS . 'com_fss' . DS . 'assets' . DS . 'images' . DS . 'blank_16.png'); } $im->resize($width, $height); $im->output(); $im_data = ob_get_clean(); if (strlen($im_data) > 0) { // if so use JFile to write the thumbnail image JFile::write($thumb_file, $im_data); } else { // it failed for some reason, try doing a direct write of the thumbnail $im->save($thumb_file); } header('Cache-control: max-age=' . 60 * 60 * 24 * 365); header('Expires: ' . gmdate(DATE_RFC1123, time() + 60 * 60 * 24 * 365)); header("Content-Type: " . $ctype); if (file_exists($thumb_file && filesize($thumb_file) > 0)) { @readfile($thumb_file); } else { $im->output(); } exit; }
function xulyImage($img, $urlImgTemp, $urlImg, $urlImgThumb, $original = 1) { $file = $urlImgTemp . $img; $sizeInfo = getimagesize($file); if (is_array($sizeInfo)) { include_once 'libraries/SimpleImage.php'; $image = new SimpleImage(); $image->load($file); $width = $sizeInfo[0]; $height = $sizeInfo[1]; if ($width <= IMAGE_THUMB_WIDTH && $height <= IMAGE_THUMB_HEIGHT) { copy($file, $urlImgThumb . $img); } elseif ($width >= $height) { $image->resizeToWidth(IMAGE_THUMB_WIDTH); $image->save($urlImgThumb . $img); } elseif ($width < $height) { $image->resizeToHeight(IMAGE_THUMB_HEIGHT); $image->save($urlImgThumb . $img); } if ($original == 1) { $image->load($file); if ($width >= $height && $width > IMAGE_MAX_WIDTH) { $image->resizeToWidth(IMAGE_MAX_WIDTH); $image->save($urlImg . $img); } elseif ($width <= $height && $height > IMAGE_MAX_HEIGHT) { $image->resizeToHeight(IMAGE_MAX_HEIGHT); $image->save($urlImg . $img); } else { copy($file, $urlImg . $img); } if (file_exists($file)) { unlink($file); } } else { if (copy($file, $urlImg . $img)) { if (file_exists($file)) { unlink($file); } } } return true; } else { return false; } }
public function get_file($modelID = '', $id = '', $filetype = '', $filename = '') { if ($id != '') { $fileinfo = $this->file_model->get_fileinfo($modelID, $id, $filetype); if ($fileinfo['Status']) { if (file_exists(absolute_path() . APPPATH . 'files/' . $fileinfo['LocalFileName'])) { switch (strtolower($filetype)) { case "thumbnails": $size = explode('_', $filename); if (!is_numeric($size[0]) or $size[0] <= 0) { show_404(); } if (!is_numeric($size[1]) or $size[0] <= 0) { show_404(); } $img = new SimpleImage(); $img->load(absolute_path() . APPPATH . 'files/' . $fileinfo['LocalFileName'])->best_fit($size[0], $size[1]); $img->output('jpg'); break; default: $mm_type = mime_content_type($fileinfo['FileName']); header('Content-Description: File Transfer'); header('Content-Type: ' . $mm_type); header('Content-Disposition: ' . $fileinfo['DispositionType'] . '; filename=' . basename($fileinfo['FileName'])); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize(APPPATH . 'files/' . $fileinfo['LocalFileName'])); ob_clean(); flush(); readfile(APPPATH . 'files/' . $fileinfo['LocalFileName']); } } } else { show_404(); } } else { show_404(); } }
private function _write_product_image($file = '', $prd_id = '') { $val = rand(999, 99999999); $image_name = "PRO" . $val . $prd_id . ".png"; //$this->upload_image($file, $image_name); $this->request->data['Product']['image'] = $image_name; $this->request->data['Product']['id'] = $prd_id; $this->Product->save($this->request->data, false); /* if (!empty($file)) { $this->FileWrite->file_write_path = PRODUCT_IMAGE_PATH; $this->FileWrite->_write_file($file, $image_name); }*/ include "SimpleImage.php"; $image = new SimpleImage(); if (!empty($file)) { $image->load($file['tmp_name']); $image->save(PRODUCT_IMAGE_PATH . $image_name); $image->resizeToWidth(150, 150); $image->save(PRODUCT_IMAGE_THUMB_PATH . $image_name); } }
public static function get($image_url, $width = NULL) { $cached_image = ''; if (!empty($image_url)) { // Get file name $exploded_image_url = explode("/", $image_url); $image_filename = end($exploded_image_url); $exploded_image_filename = explode(".", $image_filename); $extension = end($exploded_image_filename); // Image validation if (strtolower($extension) == "gif" || strtolower($extension) == "jpg" || strtolower($extension) == "png") { $cached_image = self::$image_path . $image_filename; // Check if image exists if (file_exists($cached_image)) { return $cached_image; } else { // Get remote image $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $image_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $image_to_fetch = curl_exec($ch); curl_close($ch); // Save image $local_image_file = fopen($cached_image, 'w+'); chmod($cached_image, 0755); fwrite($local_image_file, $image_to_fetch); fclose($local_image_file); // Resize image if (!is_null($width)) { $image = new SimpleImage(); $image->load($cached_image); $image->resizeToWidth($width); $image->save($cached_image); } } } } return $cached_image; }
public function bindImage($elementName) { $file = JRequest::getVar($elementName, '', 'FILES'); if (!isset($file['tmp_name']) || empty($file['tmp_name'])) { return false; } jimport('joomla.filesystem.file'); jimport('joomla.filesystem.folder'); // @task: Test if the folder containing the badges exists if (!JFolder::exists(DISCUSS_BADGES_PATH)) { JFolder::create(DISCUSS_BADGES_PATH); } // @task: Test if the folder containing uploaded badges exists if (!JFolder::exists(DISCUSS_BADGES_UPLOADED)) { JFolder::create(DISCUSS_BADGES_UPLOADED); } require_once DISCUSS_CLASSES . '/simpleimage.php'; $image = new SimpleImage(); $image->load($file['tmp_name']); if ($image->getWidth() > 64 || $image->getHeight() > 64) { return false; } $storage = DISCUSS_BADGES_UPLOADED; $name = md5($this->id . DiscussHelper::getDate()->toMySQL()) . $image->getExtension(); // @task: Create the necessary path $path = $storage . '/' . $this->id; if (!JFolder::exists($path)) { JFolder::create($path); } // @task: Copy the original image into the storage path JFile::copy($file['tmp_name'], $path . '/' . $name); // @task: Resize to the 16x16 favicon $image->resize(DISCUSS_BADGES_FAVICON_WIDTH, DISCUSS_BADGES_FAVICON_HEIGHT); $image->save($path . '/' . 'favicon_' . $name); $this->avatar = $this->id . '/' . $name; $this->thumbnail = $this->id . '/' . 'favicon_' . $name; return $this->store(); }
function imageResize($filename, $cleanFilename, $target) { if (!file_exists($cleanFilename)) { $dims = getimagesize($filename); $width = $dims[0]; $height = $dims[1]; //takes the larger size of the width and height and applies the formula accordingly...this is so this script will work dynamically with any size image if ($width > $height) { $percentage = $target / $width; } else { $percentage = $target / $height; } //gets the new value and applies the percentage, then rounds the value $width = round($width * $percentage); $height = round($height * $percentage); $image = new SimpleImage(); $image->load($filename); $image->resize($width, $height); $image->save($cleanFilename); $image = null; } //returns the new sizes in html image tag format...this is so you can plug this function inside an image tag and just get the return "src=\"{$baseurl}/{$cleanFilename}\""; }
public function bindAttachments() { $mainframe = JFactory::getApplication(); $config = DiscussHelper::getConfig(); // @task: Do not allow file attachments if its disabled. if (!$config->get('attachment_questions')) { return false; } $allowed = explode(',', $config->get('main_attachment_extension')); $files = JRequest::getVar('filedata', array(), 'FILES'); if (empty($files)) { return false; } $total = count($files['name']); // @rule: Handle empty files. if (empty($files['name'][0])) { $total = 0; } if ($total < 1) { return false; } jimport('joomla.filesystem.file'); jimport('joomla.filesystem.folder'); jimport('joomla.utilities.utility'); // @rule: Create default media path $path = DISCUSS_MEDIA . '/' . trim($config->get('attachment_path'), DIRECTORY_SEPARATOR); if (!JFolder::exists($path)) { JFolder::create($path); JFile::copy(DISCUSS_ROOT . '/index.html', $path . '/index.html'); } $maxSize = (double) $config->get('attachment_maxsize') * 1024 * 1024; for ($i = 0; $i < $total; $i++) { $extension = JFile::getExt($files['name'][$i]); // Skip empty data's. if (!$extension) { continue; } // @rule: Check for allowed extensions if (!isset($extension) || !in_array(strtolower($extension), $allowed)) { $mainframe->enqueueMessage(JText::sprintf('COM_EASYDISCUSS_FILE_ATTACHMENTS_INVALID_EXTENSION', $files['name'][$i]), 'error'); $this->setError(JText::sprintf('COM_EASYDISCUSS_FILE_ATTACHMENTS_INVALID_EXTENSION', $files['name'][$i])); return false; } else { $size = $files['size'][$i]; // @rule: File size should not exceed maximum allowed size if (!empty($size) && ($size < $maxSize || $maxSize == 0)) { $name = DiscussHelper::getHash($files['name'][$i] . DiscussHelper::getDate()->toMySQL()); $attachment = DiscussHelper::getTable('Attachments'); $attachment->set('path', $name); $attachment->set('title', $files['name'][$i]); $attachment->set('uid', $this->id); $attachment->set('type', $this->getType()); $attachment->set('created', DiscussHelper::getDate()->toMySQL()); $attachment->set('published', true); $attachment->set('mime', $files['type'][$i]); $attachment->set('size', $size); JFile::copy($files['tmp_name'][$i], $path . '/' . $name); $attachment->store(); // Create a thumbnail if attachment is an image if (DiscussHelper::getHelper('Image')->isImage($files['name'][$i])) { require_once DISCUSS_CLASSES . '/simpleimage.php'; $image = new SimpleImage(); $image->load($files['tmp_name'][$i]); $image->resizeToFill(160, 120); $image->save($path . '/' . $name . '_thumb', $image->image_type); } } else { $mainframe->enqueueMessage(JText::sprintf('COM_EASYDISCUSS_FILE_ATTACHMENTS_MAX_SIZE_EXCLUDED', $files['name'][$i], $config->get('attachment_maxsize')), 'error'); $this->setError(JText::sprintf('COM_EASYDISCUSS_FILE_ATTACHMENTS_MAX_SIZE_EXCLUDED', $files['name'][$i], $config->get('attachment_maxsize'))); return false; } } } return true; }
function check_size_and_rotation($pathname) { require_once mnminclude . "simpleimage.php"; $original = $pathname; $tmp = "{$pathname}.tmp"; $max_size = 2048; $image = new SimpleImage(); if ($image->rotate_exif($pathname)) { if ($image->save($tmp)) { $pathname = $tmp; clearstatcache(); } } if (filesize($pathname) > 1024 * 1024) { // Bigger than 1 MB if ($image->load($pathname) && ($image->getWidth() > $max_size || $image->getHeight() > $max_size)) { if ($image->getWidth() > $image->getHeight) { $image->resizeToWidth($max_size); } else { $image->resizeToHeight($max_size); } if ($image->save($tmp)) { $pathname = $tmp; clearstatcache(); } } } if ($pathname != $original && file_exists($pathname)) { if (!@rename($pathname, $original)) { syslog(LOG_INFO, "Error renaming file {$pathname} -> {$original}"); @unlink($pathname); } } $this->size = filesize($original); @chmod($original, 0777); return true; }
$uploadsDirectoryThumb = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'thumbs/'; $uploadsDirectoryThumb = str_replace("dashboard", "uploads", $uploadsDirectoryThumb); if (is_array($_FILES["file"]["error"])) { foreach ($_FILES["file"]["error"] as $key => $error) { if ($error == UPLOAD_ERR_OK) { $tmp_name = $_FILES["file"]["tmp_name"][$key]; $name = $_FILES["file"]["name"][$key]; move_uploaded_file($tmp_name, $uploadsDirectory . $hashtag . '-' . $name); $uploadedFiles[] = $hashtag . '-' . $name; } } } $image = new SimpleImage(); foreach ($uploadedFiles as $upFiles) { //resizeImage $image->load($uploadsDirectory . $upFiles); $image->resizeToWidth(133); $image->resizeToHeight(110); $image->save($uploadsDirectoryThumb . $upFiles); } $category = explode(",", $_POST['inputCategory']); foreach ($category as $key => $val) { if ($val == "") { unset($category[$key]); } else { $cats = explode("-", $val); $category[$key] = $cats[1]; } } $amenity = explode(",", $_POST['inputTags']); foreach ($amenity as $key => $val) {
$timg['Log_ID'] = 0; $timg['File_Type_ID'] = array_search($ext, $allow); $timg['User_ID'] = $_SESSION['user_id']; $timg['Original_File'] = $_FILES['uploadedfile']['name'][$u]; $insert = $db->insert("Files", $timg); $fileid = $insertid; $target_file = $target_path . $fileid . ".{$ext}"; if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'][$u], $target_file)) { $error .= "<br>The file has been uploaded</p>"; } else { $error .= "<br>There was an error uploading the file, please try again!"; $delete = $db->delete("Files", "File_ID=" . $fileid); } if (in_array($ext, $img_array)) { $image = new SimpleImage(); $image->load($target_file); $image->cropTo(150); $image->save($target_path . $fileid . '_sm.jpg'); } } elseif ($_FILES['uploadedfile']['name'][$u] != "") { $error .= "You must upload a " . implode(', ', $allow); } //echo $error; } } } } if ($_POST['redirect']) { if (strstr($_POST['redirect'], "tasks.php")) { if (strstr($_POST['redirect'], "?")) { $error = "&error=" . urlencode($error);
public function executeAvatar(sfWebRequest $request) { $this->form = new UploadAvatarForm(); $user = PcUserPeer::getLoggedInUser(); $this->isUploaded = false; if ($request->isMethod('post')) { $this->form->bind($request->getParameter('avatar'), $request->getFiles('avatar')); if ($this->form->isValid()) { $file = $this->form->getValue('file'); $extension = $file->getExtension($file->getOriginalExtension()); $filenameWithNoRandomNorExtension = $user->getForumId() . '_'; if ($file->getSize() > sfConfig::get('app_avatar_maxSize')) { die(__('ACCOUNT_SETTINGS_AVATAR_TOO_BIG')); } $random = PcUtils::generate32CharacterRandomHash(); // see generate_avatar_markup PunBB function $fileFullPathWithNoRandomNorExtension = sfConfig::get('sf_web_dir') . '/' . sfConfig::get('app_avatar_relativeRoot') . '/' . $filenameWithNoRandomNorExtension; $fileFullPath = $fileFullPathWithNoRandomNorExtension . $random . $extension; $fileFullPathWildcard = $fileFullPathWithNoRandomNorExtension . '*.*'; // {{{ deleting pre-existing files $filesToDelete = glob($fileFullPathWildcard); foreach ($filesToDelete as $fileToDelete) { unlink($fileToDelete); } /// }}} $file->save($fileFullPath); $user->setAvatarRandomSuffix($random)->save(); // resizing $image = new SimpleImage(); $image_info = getimagesize($fileFullPath); $image->load($fileFullPath); $image->resize(sfConfig::get('app_avatar_width'), sfConfig::get('app_avatar_height')); $image->save($fileFullPath, $image_info[2], 96); $this->isUploaded = true; } } $this->hasAvatar = $user->hasAvatar(); $this->avatarUrl = $user->getAvatarUrl(); }
function resizeImagesInFolder($folder) { //Time Limit vergrössern, da für viele Bilder viel Zeit in Anspruch genommen wird. set_time_limit(120); include 'includes/simpleImage.php'; $image = new SimpleImage(); if ($handle = opendir($folder)) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $bild_location = $folder . "/" . $file; $info = getimagesize($bild_location); $width = $info[0]; $height = $info[1]; echo "<b>" . $bild_location . "</b><br>"; echo 'Old width:' . $width . '<br>height:' . $height . "<br>"; if ($height > 700) { $image->load($bild_location); $image->resizeToHeight(700); $image->save($bild_location); } if ($width > 1200) { $image->load($bild_location); $image->resizeToWidth(1200); $image->save($bild_location); } $info = getimagesize($bild_location); $width = $info[0]; $height = $info[1]; echo 'New width:' . $width . '<br>height:' . $height . "<br><br><br>"; } } } return true; }
public function update_profile() { $data = array("country" => $this->input->post('country'), "province" => $this->input->post('province'), "city" => $this->input->post('city'), "address" => $this->input->post('address'), "postal" => $this->input->post('postal'), "id_card_number" => $this->input->post('id_card_number'), "phone" => $this->input->post('phone'), "im" => $this->input->post('im'), "bank_name" => $this->input->post('bank_name'), "bank_branch" => $this->input->post('bank_branch'), "bank_acc_num" => $this->input->post('bank_acc_num'), "bank_acc_name" => $this->input->post('bank_acc_name'), "fb_username" => $this->input->post('fb_username'), "fb_link" => $this->input->post('fb_link'), "last_update" => date('Y-m-d H:i:s')); if ($this->input->post('pin') != '') { $data["pin"] = md5($this->input->post('pin')); } if (isset($_POST['verify']) and $_FILES['ktp_file']['tmp_name'] == '') { if (!is_file("media/img/member_id/id_card_" . $this->session->userdata('id_member') . ".jpg")) { $this->m_member->update_member($this->session->userdata('id_member'), $data); $this->session->set_flashdata('error', "KTP harus di upload untuk proses verifikasi"); redirect("member/account_verification"); } } $this->m_member->update_member($this->session->userdata('id_member'), $data); if ($_FILES['ktp_file']['tmp_name'] != '') { $path = "media/img/member_id/"; $tmp = $_FILES['ktp_file']['tmp_name']; $size = getimagesize($tmp); $img_name = "id_card_" . $this->session->userdata('id_member') . ".jpg"; $image = new SimpleImage(); $image->load($tmp); if ($size[0] > 535) { $image->resizeToWidth(535); } $image->save($path . $img_name); } if (!isset($_POST['verify'])) { redirect("member/my_profile"); } else { $this->_is_valid(); redirect("member/account_verification"); } }
function cropImage($imagePath, $width, $height) { global $module; $folderPath = $this->crop_folder; if(!JFolder::exists($folderPath)){ JFolder::create($folderPath); } $nameImg = str_replace('/','',strrchr($imagePath,"/")); $ext = substr($nameImg, strrpos($nameImg, '.')); $file_name = substr($nameImg, 0, strrpos($nameImg, '.')); $nameImg = str_replace(" ","",$file_name . "_" . $width . "_" . $height . $ext); if(!JFile::exists($folderPath.DS.$nameImg)){ $image = new SimpleImage(); $image->load($imagePath); $image->crop($width,$height); $image->save($folderPath.DS.$nameImg); }else{ list($info_width, $info_height) = @getimagesize($folderPath.DS.$nameImg); if($width!=$info_width||$height!=$info_height){ $image = new SimpleImage(); $image->load($imagePath); $image->crop($width,$height); $image->save($folderPath.DS.$nameImg); } } return $this->url_to_crop . $nameImg; }