public function redactorUploadImage() { $file = Input::file('file'); $uploadPath = public_path('uploads'); if (Input::hasFile('file')) { $fileName = str_random(16) . '.' . Input::file('file')->getClientOriginalExtension(); if (!File::exists($uploadPath . '/thumbnail')) { File::makeDirectory($uploadPath . '/thumbnail', 0777, TRUE); } /* ImageManipulation::make(Input::file('file')->getRealPath())->resize(100, 100)->save($uploadPath . '/thumbnail/thumb_' . $fileName); ImageManipulation::make(Input::file('file')->getRealPath())->resize(600, 600)->save($uploadPath . '/' . $fileName); */ ## Pathes $uploadPath = Config::get('site.uploads_photo_dir'); $thumbsPath = Config::get('site.uploads_thumb_dir'); $uploadPathPublic = Config::get('site.uploads_photo_public_dir'); $thumbsPathPublic = Config::get('site.uploads_thumb_public_dir'); if (!File::exists($uploadPath)) { File::makeDirectory($uploadPath, 0777, TRUE); } if (!File::exists($thumbsPath)) { File::makeDirectory($thumbsPath, 0777, TRUE); } ## Resize thumb image $thumb_upload_success = ImageManipulation::make($file->getRealPath())->resize(200, 200, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); })->save($thumbsPath . '/' . $fileName); ## Resize full-size image $image_upload_success = ImageManipulation::make($file->getRealPath())->resize(1280, 1280, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); })->save($uploadPath . '/' . $fileName); #$file = array('filelink'=>url('uploads/'.$fileName)); $file = array('filelink' => $uploadPathPublic . '/' . $fileName); #return Response::json($file); echo stripslashes(json_encode($file)); die; } else { exit('Нет файла для загрузки!'); } }
/** * getAdapterLoader * @return Zend_Loader_PluginLoader * @author Cornelius Hansjakob <*****@*****.**> * @version 1.0 */ public static function getAdapterLoader() { if (null === self::$objAdapterLoader) { require_once 'Zend/Loader/PluginLoader.php'; self::$objAdapterLoader = new Zend_Loader_PluginLoader(array('ImageAdapter' => dirname(__FILE__) . '/adapter/')); } return self::$objAdapterLoader; }
/** * @desc Generic functuion to upload media from the $_FILES array, also saves the data into the DB * @param $to_table * @param $to_table_id * @return $uploaded files array * @author Peter Ivanov * @version 1.0 * @since Version 1.0 */ function mediaUpload($to_table, $to_table_id, $queue_id = false, $resize_options = false) { $target_path = MEDIAFILES; $uploaded = array(); if (empty($_FILES)) { return false; } $this->load->library('upload'); if (!empty($_FILES)) { $params['session_id'] = $this->input->post("PHPSESSID"); //load the session library the new way, by passing it the session id // $this->load->library('session', $params); $this->cleanCacheGroup('media/global'); require_once APPPATH . 'libraries/' . 'ImageManipulation.php'; foreach ($_FILES as $k => $item) { if (stristr($k, 'picture_') == true) { $target_path = MEDIAFILES; $filename = basename($_FILES[$k]['name']); if (strval($filename) != '') { $filename = strtolower($filename); $path = $target_path . 'pictures/'; if (is_dir($path) == false) { @mkdir($path); //@chmod ( $path, '0777' ); } $the_target_path = $target_path . 'pictures/original/'; $original_path = $the_target_path; if (is_dir($the_target_path) == false) { @mkdir($the_target_path); //@chmod ( $the_target_path, '0777' ); } $the_target_path = $the_target_path . $this->url_title($filename, $separator = 'dash', $no_slashes = false, $leave_dots = true); if (is_file($the_target_path) == true) { $filename = date("ymdHis") . basename($_FILES[$k]['name']); $filename = $this->url_title($filename, $separator = 'dash', $no_slashes = false, $leave_dots = true); $the_target_path = $original_path . $filename; } if (move_uploaded_file($_FILES[$k]['tmp_name'], $the_target_path)) { if (is_file($the_target_path) == true) { if (is_readable($the_target_path) == true) { if (!empty($resize_options)) { $objImage = false; $objImage = new ImageManipulation($the_target_path); if ($objImage->imageok) { $img_info = $objImage->image; $sizex = $img_info['sizex']; //var_dump($sizex); if (intval($resize_options['width']) < intval($sizex) and intval($resize_options['width']) > 1) { $objImage->resize(intval($resize_options['width'])); $objImage->save($the_target_path); } } } $uploaded[$k] = $this->url_title($filename, $separator = 'dash', $no_slashes = false, $leave_dots = true); } } } } if (empty($uploaded)) { return false; } else { $sizes = array(); $sizes = $this->optionsGetByKeyAsArray('media_image_sizes'); foreach ($uploaded as $item) { $extension = substr(strrchr($item, '.'), 1); foreach ($sizes as $size) { $image = $original_path . $item; $newimage = $path . "{$size}/"; if (is_dir($newimage) == false) { @mkdir($newimage); } $newimage = $path . "{$size}/" . $item; $image_quality = 80; $max_height = $size; $max_width = $size; switch ($extension) { case 'jpg': case 'jpeg': $src_img = ImageCreateFromJpeg($image); $orig_x = ImageSX($src_img); $orig_y = ImageSY($src_img); $new_y = $max_height; $new_x = $orig_x / ($orig_y / $max_height); if ($new_x > $max_width) { $new_x = $max_width; $new_y = $orig_y / ($orig_x / $max_width); } $dst_img = ImageCreateTrueColor($new_x, $new_y); ImageCopyResampled($dst_img, $src_img, 0, 0, 0, 0, $new_x, $new_y, $orig_x, $orig_y); ImageJpeg($dst_img, $newimage, $image_quality); ImageDestroy($src_img); ImageDestroy($dst_img); break; case 'gif': $src_img = imagecreatefromgif($image); $orig_x = ImageSX($src_img); $orig_y = ImageSY($src_img); $new_y = $max_height; $new_x = $orig_x / ($orig_y / $max_height); if ($new_x > $max_width) { $new_x = $max_width; $new_y = $orig_y / ($orig_x / $max_width); } $dst_img = ImageCreateTrueColor($new_x, $new_y); ImageCopyResampled($dst_img, $src_img, 0, 0, 0, 0, $new_x, $new_y, $orig_x, $orig_y); imagegif($dst_img, $newimage, $image_quality); ImageDestroy($src_img); ImageDestroy($dst_img); break; case 'png': $src_img = imagecreatefrompng($image); $orig_x = ImageSX($src_img); $orig_y = ImageSY($src_img); $new_y = $max_height; $new_x = $orig_x / ($orig_y / $max_height); if ($new_x > $max_width) { $new_x = $max_width; $new_y = $orig_y / ($orig_x / $max_width); } $im_dest = imagecreatetruecolor($new_x, $new_y); imagealphablending($im_dest, false); imagecopyresampled($im_dest, $src_img, 0, 0, 0, 0, $new_x, $new_y, $orig_x, $orig_y); imagesavealpha($im_dest, true); imagepng($im_dest, $newimage); imagedestroy($im_dest); break; } } } } } } global $cms_db_tables; $table = $cms_db_tables['table_media']; $media_table = $table; foreach ($uploaded as $item) { if (strval($item) != '') { $media_save = array(); $media_save['media_type'] = 'picture'; $media_save['filename'] = $item; $media_save['to_table'] = $to_table; $media_save['to_table_id'] = $to_table_id; $new_media_id = $this->saveData($table, $media_save); $media_save['id'] = $new_media_id; } } // if (trim($to_table) != '' and trim($to_table_id) != '') { $cache_group = "media/{$to_table}/{$to_table_id}"; $this->cleanCacheGroup($cache_group); } $res = $media_save; $this->cleanCacheGroup('media/global'); $this->mediaFixOrder($to_table, $to_table_id, 'picture'); return $res; } else { return false; } // exit (); }
function crop_picture_by_id() { @ob_clean(); $user_id = CI::model('core')->userId(); if (intval($user_id) == 0) { exit('Error! You are not logged in.'); } $id = $_POST['id']; if ($id > 0) { $media = CI::model('core')->mediaGetById($id); if (!empty($media)) { require 'ImageManipulation.php'; $file_path = MEDIAFILES . 'pictures/original/' . $media['filename']; $objImage = new ImageManipulation($file_path); if ($objImage->imageok) { $objImage->setCrop($_POST['x'], $_POST['y'], $_POST['w'], $_POST['h']); //$objImage->resize(500); //$objImage->show(); $objImage->save($file_path); } else { echo 'Error!'; } } } // $src = 'flowers.jpg'; //exit (); exit; //var_dump ( $_POST ); }
/** * Ссылка на изображение, подвергнутое кропу или ресайзу * * URL::route('image.resize', [$photo->id, 200, 200]) * URL::route('image.resize', [$photo->id, 200, 200, 'r']) * * См. также /app/config/site.php * - galleries_cache_public_dir * - galleries_cache_allowed_sizes * * @param string $method Method of resize - crop or resize */ public function getImageResize($image_id, $w, $h, $method = 'crop') { $image = $image_id ? Photo::find($image_id) : null; #Helper::tad($method); /** * Костылек-с */ if (is_numeric($method)) { $h = $h * 10 + $method; #$method = 'crop'; } if ($method == 'r') { $method = 'resize'; } else { $method = 'crop'; } #Helper::tad($method); /** * Соблюдены ли все правила? */ if (!$image_id || !$image || !is_object($image) || !@file_exists($image->fullpath()) || !$w || !$h || $w < 0 || $h < 0 || !in_array($w . 'x' . $h, (array) Config::get('site.galleries_cache_allowed_sizes')) || !in_array($method, ['crop', 'resize'])) { App::abort(404); } /* Helper::ta($image_id . '_' . $w . 'x' . $h . $method . '.jpg'); Helper::ta($image->fullpath()); Helper::ta($image->fullcachepath($w, $h, $method)); Helper::ta($image->cachepath($w, $h, $method)); #Helper::tad($image->full()); */ if (!File::exists(Config::get('site.galleries_cache_dir'))) { File::makeDirectory(Config::get('site.galleries_cache_dir'), 0777, TRUE); } $img = ImageManipulation::make($image->fullpath()); if ($method == 'resize') { /** * Resize + Resize Canvas */ $img->resize($w, $h, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); }); $img->resizeCanvas($w, $h); /* $newimg = ImageManipulation::canvas($w, $h); $newimg->insert($img, 'center'); $img = $newimg; #$newimg->destroy(); #*/ } else { /** * Resize + Crop */ /** * Текущие значения ширины и высоты */ $rw = $img->width(); $rh = $img->height(); /** * Находим требуемые коэффициенты */ $c1 = $rw / $w; ## Делим реальную ширину на желаемую $c2 = $rh / $h; ## Делим реальную высоту на желаемую /** * Если c1 < c2 - то ресайзить нужно по ширине * Если c1 > c2 - то ресайзить нужно по высоте */ if ($c1 < $c2) { /** * Ресайзим по меньшей стороне, по ширине */ $nw = $w; $nh = null; } else { /** * Ресайзим по меньшей стороне, по высоте */ $nw = null; $nh = $h; } #Helper::tad($nw . 'x' . $nh); $img->resize($nw, $nh, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); }); /** * Новые значения ширины и высоты, после ресайза по меньшей стороне */ $nnw = $img->width(); $nnh = $img->height(); /** * Кроп по центру по заданным размерам */ $img->crop($w, $h, ceil(($nnw - $w) / 2), ceil(($nnh - $h) / 2)); } /** * Сохраняем изображение */ $img->save($image->fullcachepath($w, $h, $method), 90); /** * Отдаем изображение в браузер */ header('Debug-ImageSource: onthefly'); return $img->response(); }
private function uploadImage($input_file_name = 'file') { $result = array('result' => 'error'); ## Check data if (is_string($input_file_name)) { if (!Input::hasFile($input_file_name)) { $result['desc'] = 'No input file.'; return $result; } $file = Input::file($input_file_name); } elseif (is_object($input_file_name)) { $file = $input_file_name; } $rules = array('file' => 'image'); $validation = Validator::make(array('file' => $file), $rules); if ($validation->fails()) { $result['desc'] = 'This extension is not allowed.'; return $result; } ## Check upload & thumb dir $uploadPath = Config::get('site.galleries_photo_dir'); $thumbsPath = Config::get('site.galleries_thumb_dir'); if (!File::exists($uploadPath)) { File::makeDirectory($uploadPath, 0777, TRUE); } if (!File::exists($thumbsPath)) { File::makeDirectory($thumbsPath, 0777, TRUE); } ## Generate filename srand((double) microtime() * 1000000); $fileName = time() . "_" . rand(1000, 1999) . '.' . $file->getClientOriginalExtension(); ## Get images resize parameters from config $thumb_size = Config::get('site.galleries_thumb_size'); $photo_size = Config::get('site.galleries_photo_size'); ## Get image width & height $image = ImageManipulation::make($file->getRealPath()); $w = $image->width(); $h = $image->height(); if ($thumb_size > 0) { ## Normal resize $thumb_resize_w = $thumb_size; $thumb_resize_h = $thumb_size; } else { ## Resize "by the smaller side" $thumb_size = abs($thumb_size); ## Resize thumb & full-size images "by the smaller side". ## Declared size will always be a minimum. $thumb_resize_w = $w > $h ? null : $thumb_size; $thumb_resize_h = $w > $h ? $thumb_size : null; } ## Resize thumb image $thumb_upload_success = ImageManipulation::make($file->getRealPath())->resize($thumb_resize_w, $thumb_resize_h, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); })->save($thumbsPath . '/' . $fileName); if ($photo_size > 0) { ## Normal resize $image_resize_w = $photo_size; $image_resize_h = $photo_size; } else { ## Resize "by the smaller side" $photo_size = abs($photo_size); ## Resize full-size images "by the smaller side". ## Declared size will always be a minimum. $image_resize_w = $w > $h ? null : $photo_size; $image_resize_h = $w > $h ? $photo_size : null; } ## Resize full-size image $image_upload_success = ImageManipulation::make($file->getRealPath())->resize($image_resize_w, $image_resize_h, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); })->save($uploadPath . '/' . $fileName); if (!$thumb_upload_success || !$image_upload_success) { $result['desc'] = 'Error on the saving images.'; return $result; } $result['result'] = 'success'; $result['filename'] = $fileName; return $result; }
$file_name = $file_name . '.png'; break; case 'image/gif': $file_name = $file_name . '.gif'; break; default: $file_name = $file_name . '.jpg'; break; } //apply the file path $file_src_new = $file_path . '/' . $file_name; //Chmod the folder //$CORE->ChmodWritable($file_path); //we've got no error $error = false; $objImage = new ImageManipulation($file_src); if ($objImage->imageok) { $objImage->setJpegQuality(100); $objImage->setCrop($_POST['x'], $_POST['y'], $_POST['w'], $_POST['h']); if ($resize) { if ($imageInfo[0] > $resize or $imageInfo[0] < $resize) { $objImage->resize($resize); } } //$objImage->show(); $objImage->save($file_src_new); @unlink($file_src); } else { $error = '@AjaxError@Epic Fail. Please contact the administration.'; } //check for website failure
//Define the temp upload folder $tempFolder = $config['RootPath'] . '/admin/tempUploads'; //Let's start by creating a folder for the movie $MovieFolder = preg_replace('/[^A-Za-z0-9-_]/', '', $title) . '_' . $uniqer; $DirName = $MovieFolder; //append the full path $MovieFolder = $config['RootPath'] . '/uploads/media/movies/' . $MovieFolder; //Create the movie directory if (!mkdir($MovieFolder, 0755, true)) { $ERRORS->Add("The website was not able to create new directory for the movie."); } $ImageFolder = $MovieFolder . '/thumbnails'; //Create a folder for the images aswell mkdir($ImageFolder, 0755, true); //Let's start creating diferent size thumbs $objImage = new ImageManipulation($tempFolder . '/' . $image); //Verify the image if ($objImage->imageok) { $objImage->setJpegQuality(100); //Start by making the default size image, no resize $objImage->save($ImageFolder . '/' . $image); //Index image 401x227 $objImage->resize(401); $objImage->save($ImageFolder . '/index_' . $image); //Medium image 255x145 $objImage->resize(255); $objImage->save($ImageFolder . '/medium_' . $image); //Small image 200x113 $objImage->resize(200); $objImage->save($ImageFolder . '/small_' . $image); //delete the temp
public static function createImageInBase64String($input = 'file') { $base62string = Input::get($input); if (!empty($base62string)) { $fileName = time() . "_" . Auth::user()->id . "_" . rand(1000, 1999) . '.png'; ImageManipulation::make($base62string)->resize(110, 110)->save(Config::get('site.uploads_thumb_dir') . '/thumb_' . $fileName); ImageManipulation::make($base62string)->resize(157, 157)->save(Config::get('site.uploads_photo_dir') . '/' . $fileName); return array('main' => Config::get('site.uploads_photo_public_dir') . '/' . $fileName, 'thumb' => Config::get('site.uploads_thumb_public_dir') . '/thumb_' . $fileName); } return FALSE; }
//apply the file path $file_src_new = $file_path . '/' . $imageName; //thumb $file_src_new_thumb = $file_path . $thumb_folder . '/' . $imageName; //Chmod the folder //$CORE->ChmodWritable($file_path); //$CORE->ChmodWritable($file_path . $thumb_folder); //handle the upload if (move_uploaded_file($tempFile, $file_src_new)) { //try deleting the temp file @unlink($tempFile); } else { $ERRORS->Add("The website failed to upload your screenshot. If this problem presists please contact the administration."); } //resample the image $objImage = new ImageManipulation($file_src_new); if ($objImage->imageok) { //resample the image $objImage->setJpegQuality(100); $objImage->save($file_src_new); //make a thumb $objImage->resizeProper($thumb_width, $thumb_height); $objImage->save($file_src_new_thumb); //get the time $time = $CORE->getTime(); $type = TYPE_SCREENSHOT; $status = SCREENSHOT_STATUS_PENDING; //insert into the database $insert = $DB->prepare("INSERT INTO `images` (`name`, `descr`, `added`, `account`, `image`, `type`, `status`) VALUES (:name, :descr, :added, :account, :image, :type, :status);"); $insert->bindParam(':name', $title, PDO::PARAM_STR); $insert->bindParam(':descr', $descr, PDO::PARAM_STR);
<?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $src = 'google.png'; require 'ImageManipulation.php'; $objImage = new ImageManipulation($src); if ($objImage->imageok) { $objImage->setCrop($_POST['x'], $_POST['y'], $_POST['w'], $_POST['h']); $objImage->resize(500); $objImage->show(); // uncomment the following line to save the output image. $objImage->save('12345.png'); } else { echo 'Error!'; } exit; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>--> <!--<script src="jquery.Jcrop.pack.js" type="text/javascript"></script>--> <script src="./js/jquery.min.js" type="text/javascript"></script> <script src="./js/jquery.Jcrop.js" type="text/javascript"></script> <script src="./js/jquery.color.js" type="text/javascript"></script> <link rel="stylesheet" href="./css/jquery.Jcrop.css" type="text/css" /> <link rel="stylesheet" href="./css/jquery.Jcrop.extras.css" type="text/css" /> <!--<link rel="stylesheet" href="demo_files/demos.css" type="text/css" />-->
//echo ($h . " " . $aspectratio); } } echo " " . $actualwidth; echo " " . $actualheight; /* } else if ($aspectratio < 1) { echo ("height100% "); $w = ceil($dropHeight * $aspectratio); echo ($w . " " . $aspectratio); } */ } else { if ($type == "CropImage") { if ($_SERVER['REQUEST_METHOD'] == 'POST') { $src = $_POST['src']; require './javascripts/plugins/croping/ImageManipulation.php'; $objImage = new ImageManipulation($src); if ($objImage->imageok) { $objImage->setCrop($_POST['x'], $_POST['y'], $_POST['w'], $_POST['h']); $objImage->resize(500); $filename_ext = pathinfo($src, PATHINFO_EXTENSION); $src = preg_replace('/(\\.gif|\\.jpg|\\.png)/', '1', "{$src}"); $src = $src . "." . $filename_ext; $objImage->save($src); } else { echo 'Error!'; } exit; } } else { if ($type == "getSideButtons") { session_start();
//mega: AIzaSyALc9l8tOL3WZiGQ1Av3CsLsJdZyt477KA //noname: AIzaSyC9VwjNP3Yrk0pdsQeidKMuVJhnj70OfA0 use_javascript("https://www.google.com/jsapi?key=AIzaSyC9VwjNP3Yrk0pdsQeidKMuVJhnj70OfA0"); //See https://code.google.com/apis/console/#project:326513611386:overview use_javascript("formatted_colors.js"); use_javascript("google_images.js"); //use_javascript("jquery-ui.js"); //use_stylesheet("jquery-ui.css"); use_javascript("base64.js"); use_javascript("canvas2image.js"); if (isset($img_path)) { ?> <div class="mosaic-wrapper"> <?php $img = ImageManipulation::imagecreatefrom($img_path); //Returns Image object. MosaicGenerator::printCanvasMosaic($img, $cell_size, $keywords); //Defines three Javascript variables: The color matrix, the size of each image, and the keywords. ?> <script src="/js/generate_mosaic.js"> </script> <!-- Picks up three variables from printCanvasMosaic(), creates canvas mosaic !--> <div class="mosaic-actions"> <div class="tweak-size"> <p>Mosaic Size: </p> <select> <option value="300">Small </option> <option value="600" selected>Medium </option> <option value="900">Large </option> <option value="1600">Huge </option> </select>
/** * generate a thumbnail * @param str $sub_path upload path * @param str $file filename * @param str $out_file outfile name, can be null if show is true * @param int $w desired width * @param int $h desired max height, optional, will limit height and adjust width accordingly * @param int $quality quality of image jpg and png * @param bool $show output to browser if true * @param str $output_format optional output format, if not determining from out_file can be excusivly set (1|'GIF', 2|'JPG,'' 3|'PNG') * @param boolean $upscale true, allows image to scale up/zoom to fit thumbnail * @return bool success */ function generate_thumbnail($file, $sub_path = '', $out_file = null, $w = null, $h = null, $crop = null, $quality = null, $show = false, $output_format = null, $upscale = false) { //gd check, do nothing if no gd $php_modules = get_loaded_extensions(); if (!in_arrayi('gd', $php_modules)) { return false; } $sub_path = tsl($sub_path); $upload_folder = GSDATAUPLOADPATH . $sub_path; $thumb_folder = GSTHUMBNAILPATH . $sub_path; $thumb_file = isset($out_file) && !empty($out_file) ? $thumb_folder . $out_file : ''; create_dir($thumb_folder); require_once 'imagemanipulation.php'; $objImage = new ImageManipulation($upload_folder . $file); if ($objImage->imageok) { if ($upscale) { $objImage->setUpscale(); } // allow magnification if ($quality) { $objImage->setQuality($quality); } // set quality for jpg or png if (isset($output_format)) { $objImage->setOutputFormat($output_format); } // setoutput format, ignored if out_file specifies extension if (isset($w) && isset($h)) { $objImage->setImageWidth($w, $h); } elseif (isset($w)) { $objImage->setImageWidth($w); // if only specifiying width, scale to width only // $objImage->resize($w); // constrains both dimensions to $size, same as setImageWidth($w,$w); } elseif (isset($h)) { $objImage->setImageHeight($h); // if only specifiying width, scale to width only } if (isset($crop)) { $objImage->setAutoCrop($crop); } // die(print_r($objImage)); $objImage->save($thumb_file, $show); return $objImage; } else { return false; } }
private function cleanFilename() { $name = $this->file['name']; if ($name === "" || $name == null) { trigger_error("Filename is empty!", E_USER_ERROR); } // removes illegal characters $badChars = array('/', '\\', '?', '%', '*', ':', '|', '"', '<', '>', ',', "-", "_"); $name = str_replace($badChars, "", $name); // if the whole string concisted of illegals, randomize new name while ($name == "") { $name = substr(md5(uniqid() . rand()), 0, 5); } if (preg_match("/.*\\..+/i", $name) == 0) { switch (ImageManipulation::getMime($this->file['tmp_name'])) { case 'image/jpeg': case 'image/jpeg; charset=binary': $name .= ".jpg"; break; case 'image/png': case 'image/png; charset=binary': $name .= ".png"; break; case 'image/gif': case 'image/gif; charset=binary': $name .= ".gif"; break; default: trigger_error("Unsupported mime type, I wont give {$name} a file extension!", E_USER_NOTICE); } } // fixes $name = preg_replace("/(.*?)([!.]+)(\\.)(jpg|gif|jpeg|png)(.*)/", "{${2}}.{${4}}", $name); while (file_exists(I_IMAGE_DIR . DIRECTORY_SEPARATOR . $name) || file_exists(I_THUMBNAIL_DIR . DIRECTORY_SEPARATOR . $name)) { $name = rand() % 10 . $name; } $this->file['safeName'] = $name; }
public static function upload($url, $gallery = NULL, $title = '') { $img_data = @file_get_contents($url); if (!$img_data) { return false; } $tmp_path = storage_path(md5($url)); try { file_put_contents($tmp_path, $img_data); } catch (Exception $e) { echo 'Error #' . $e->getCode() . ':' . $e->getMessage() . "<br/>\n"; echo 'In file: ' . $e->getFile() . ' (' . $e->getLine() . ')'; die; } $file = new \Symfony\Component\HttpFoundation\File\UploadedFile($tmp_path, basename($url)); ## Check upload & thumb dir $uploadPath = Config::get('site.galleries_photo_dir'); $thumbsPath = Config::get('site.galleries_thumb_dir'); if (!File::exists($uploadPath)) { File::makeDirectory($uploadPath, 0777, TRUE); } if (!File::exists($thumbsPath)) { File::makeDirectory($thumbsPath, 0777, TRUE); } ## Generate filename $fileName = time() . "_" . rand(1000, 1999) . '.' . $file->getClientOriginalExtension(); #echo $fileName; ## Get images resize parameters from config $thumb_size = Config::get('site.galleries_thumb_size'); $photo_size = Config::get('site.galleries_photo_size'); ## Get image width & height $image = ImageManipulation::make($file->getRealPath()); $w = $image->width(); $h = $image->height(); if ($thumb_size > 0) { ## Normal resize $thumb_resize_w = $thumb_size; $thumb_resize_h = $thumb_size; } else { ## Resize "by the smaller side" $thumb_size = abs($thumb_size); ## Resize thumb & full-size images "by the smaller side". ## Declared size will always be a minimum. $thumb_resize_w = $w > $h ? null : $thumb_size; $thumb_resize_h = $w > $h ? $thumb_size : null; } ## Resize thumb image $thumb_upload_success = ImageManipulation::make($file->getRealPath())->resize($thumb_resize_w, $thumb_resize_h, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); })->save($thumbsPath . '/' . $fileName); if ($photo_size > 0) { ## Normal resize $image_resize_w = $photo_size; $image_resize_h = $photo_size; } else { ## Resize "by the smaller side" $photo_size = abs($photo_size); ## Resize full-size images "by the smaller side". ## Declared size will always be a minimum. $image_resize_w = $w > $h ? null : $photo_size; $image_resize_h = $w > $h ? $photo_size : null; } ## Resize full-size image $image_upload_success = ImageManipulation::make($file->getRealPath())->resize($image_resize_w, $image_resize_h, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); })->save($uploadPath . '/' . $fileName); ## Delete original file unlink($file->getRealPath()); ## Gallery - none, existed, new $gallery_id = 0; if (is_int($gallery) && $gallery > 0) { $gallery_id = $gallery; } elseif (is_string($gallery)) { $gal = Gallery::create(['name' => $gallery]); $gallery_id = $gal->id; } ## Create MySQL record $photo = Photo::create(array('name' => $fileName, 'gallery_id' => $gallery_id, 'title' => $title)); return $photo; }
public function byURL($url) { if (!isset($url) || !is_string($url)) { trigger_error("Invalid input!", E_USER_ERROR); } // check if the image is downloadable $curlHandle = curl_init(); curl_setopt_array($curlHandle, array(CURLOPT_URL => $url, CURLOPT_NOBODY => true, CURLOPT_HEADER => false)); $res = curl_exec($curlHandle); if (!$res) { return "-11\nFile doesn't exist!"; } $i = curl_getinfo($curlHandle); if ($i['download_content_length'] > MAX_FILE_SIZE) { return "-12\nFile too large!"; } // Download the image! $this->file['tmp_name'] = tempnam("/tmp", "i2"); $fileHandle = fopen($this->file['tmp_name'], 'w'); $curlHandle = curl_init(); curl_setopt_array($curlHandle, array(CURLOPT_URL => $url, CURLOPT_FILE => $fileHandle, CURLOPT_CONNECTTIMEOUT => DOWNLOAD_TIMEOUT, CURLOPT_BINARYTRANSFER => 1)); $download = curl_exec($curlHandle); fclose($fileHandle); if (curl_errno($curlHandle) != 0) { return "-13\nInternal cURL error: (" . curl_errno($curlHandle) . ") " . curl_error($curlHandle); } $this->file['hash'] = hash_file("md5", $this->file['tmp_name']); // checks if image is new and if not only grants the image a new // timestamp $res = SQL::query("SELECT COUNT(*) as images FROM images" . " WHERE hash = '" . $this->file['hash'] . "' LIMIT 1"); if ($res->fetch_object()->images > 0) { trigger_error("Hash is not unique, will only update image", E_USER_NOTICE); SQL::query("UPDATE images SET images.time = '" . time() . "' " . "WHERE hash = '" . $this->file['hash'] . "' LIMIT 1"); return "2\nSuccess! Image updated in database!"; } else { $this->file['name'] = split('/', $url); $this->file['name'] = $this->file['name'][count($this->file['name']) - 1]; $this->cleanFilename(); if (!copy($this->file['tmp_name'], I_IMAGE_DIR . DIRECTORY_SEPARATOR . $this->file['safeName'])) { return "-14\nCould not copy file to image directory"; } $manip = new ImageManipulation($this->file['tmp_name']); $manip->thumbnail(); $manip->save(I_THUMBNAIL_DIR . DIRECTORY_SEPARATOR . $this->file['safeName']); unset($manip); $this->insertIntoDB(); return "1\nSuccess! '" . $this->file['safeName'] . "' uploaded!"; } }
<?php require_once '../core/init.php'; if (Input::exists()) { if (Token::check(Input::get('token'))) { $validate = new Validate(); $profile_pic_check = $validate->ImageCheck(Input::get('profile_pic')); $email = $validate->email(Input::get('email')); //make sure $validation is the last validation check because it makes sure there are no errors in total(including image errors.) $validation = $validate->check($_POST, array('username' => ['fieldname' => 'Username', 'required' => true, 'min' => 3, 'max' => 20, 'unique' => 'users', 'contains' => 'alnum(m:letters)'], 'password' => ['fieldname' => 'Password', 'required' => true, 'min' => 6], 'name' => ['fieldname' => 'Name', 'required' => true, 'min' => 2, 'max' => 50], 'email' => ['fieldname' => 'Email', 'min' => 3, 'max' => 320, 'unique' => 'users'])); if ($validation->passed()) { if ($profile_pic_check === false) { $profilePicDest = 'images/default_profile_pic.jpg'; } else { $image = new ImageManipulation(Input::get('profile_pic')); $image->moveTo('images/uploads/'); $profilePicDest = $image->getNewDest(); } $user = new User(); $salt = Hash::salt(32); $email_code = md5(Input::get('username') . microtime()); try { $user->create(['username' => Input::get('username'), 'password' => Hash::make(Input::get('password'), $salt), 'salt' => $salt, 'fullname' => strip_excess(Input::get('name')), 'email' => $email, 'profile_pic' => $profilePicDest]); /* * TODO: Email Activation Up and Running. V(1.0) * $mail = new Email; * $mail->sendGmailActivation(BASE_URL . 'activate/' . $email_code ); * */ Session::flash('success', 'You registered successfully!'); Redirect::to(BASE_URL); } catch (Exception $e) {
/** * renderAllImages * @author Cornelius Hansjakob <*****@*****.**> * @version 1.0 */ public function renderAllImages() { $this->core->logger->debug('massiveart.images.Image->renderAllImages()'); try { $this->getModelFile(); /** * check public file path */ $this->checkPublicFilePath(); $objImageFiles = $this->objModelFile->getAllImageFiles(); if (count($objImageFiles) > 0) { foreach ($objImageFiles as $objImageFile) { $srcFile = $this->getUploadPath() . $objImageFile->filename; if (count($this->arrDefaultImageSizes) > 0) { $objImageManipulation = new ImageManipulation(); $objImageManipulation->setAdapterType($this->core->sysConfig->upload->images->adapter); /** * get image manipulation adapter */ $objImageAdapter = $objImageManipulation->getAdapter(); $objImageAdapter->setRawWidth($objImageFile->xDim); $objImageAdapter->setRawHeight($objImageFile->yDim); /** * render default image sizes */ foreach ($this->arrDefaultImageSizes as $arrImageSize) { $objImageAdapter->setSource($srcFile); $objImageAdapter->setDestination($this->getPublicFilePath() . $arrImageSize['folder'] . '/' . $objImageFile->filename); $this->checkPublicFilePath($arrImageSize['folder'] . '/'); if (array_key_exists('actions', $arrImageSize) && is_array($arrImageSize['actions'])) { if (array_key_exists('method', $arrImageSize['actions']['action'])) { $arrAction = $arrImageSize['actions']['action']; $strMethode = $arrAction['method']; $arrParams = array_key_exists('params', $arrAction) ? explode(',', $arrAction['params']) : array(); if (method_exists($objImageAdapter, $strMethode)) { call_user_func_array(array($objImageAdapter, $strMethode), $arrParams); } } else { foreach ($arrImageSize['actions']['action'] as $arrAction) { if (array_key_exists('method', $arrAction)) { $strMethode = $arrAction['method']; $arrParams = array_key_exists('params', $arrAction) ? explode(',', $arrAction['params']) : array(); if (method_exists($objImageAdapter, $strMethode)) { call_user_func_array(array($objImageAdapter, $strMethode), $arrParams); } } } } } } } } } } catch (Exception $exc) { $this->core->logger->err($exc); } }
// Variable Settings login_cookie_check(); $subPath = isset($_GET['path']) ? $_GET['path'] : ""; if ($subPath != '') { $subPath = tsl($subPath); } $src = strippath($_GET['i']); $thumb_folder = GSTHUMBNAILPATH . $subPath; $src_folder = '../data/uploads/'; $thumb_folder_rel = '../data/thumbs/' . $subPath; if (!is_file($src_folder . $subPath . $src)) { redirect("upload.php"); } if ($_SERVER['REQUEST_METHOD'] == 'POST') { require_once 'inc/imagemanipulation.php'; $objImage = new ImageManipulation($src_folder . $subPath . $src); if ($objImage->imageok) { $objImage->setCrop($_POST['x'], $_POST['y'], $_POST['w'], $_POST['h']); //$objImage->show(); $objImage->save($thumb_folder . 'thumbnail.' . $src); $success = i18n_r('THUMB_SAVED'); } else { i18n('ERROR'); } } list($imgwidth, $imgheight, $imgtype, $imgattr) = getimagesize($src_folder . $subPath . $src); if (file_exists($thumb_folder . 'thumbnail.' . $src)) { list($thwidth, $thheight, $thtype, $athttr) = getimagesize($thumb_folder . 'thumbnail.' . $src); $thumb_exists = ' | <a href="' . $thumb_folder_rel . 'thumbnail.' . rawurlencode($src) . '" rel="facybox_i" >' . i18n_r('CURRENT_THUMBNAIL') . '</a> <code>' . $thwidth . 'x' . $thheight . '</code>'; } else { require_once 'inc/imagemanipulation.php';
$thumb_url = tsl($SITEURL) . $thumb_folder_rel; if (!filepath_is_safe($src_folder . $subPath . $src, GSDATAUPLOADPATH)) { redirect("upload.php"); } // handle jcrop thumbnail creation if ($_SERVER['REQUEST_METHOD'] == 'POST' && matchArrayAll(array('x', 'y', 'w', 'h'), array_keys($_POST))) { exec_action('image-crop'); $x = (int) $_POST['x']; $y = (int) $_POST['y']; $w = (int) $_POST['w']; $h = (int) $_POST['h']; $max = 10000; // set a max to prevent excessive processing injections if ($x < $max && $y < $max && $w < $max && $h < $max) { require_once 'inc/imagemanipulation.php'; $objImage = new ImageManipulation($src_folder . $subPath . $src); if ($objImage->imageok) { $objImage->setCrop($x, $y, $w, $h); $objImage->save($thumb_folder . 'thumbnail.' . $src); $success = i18n_r('THUMB_SAVED'); } else { $error = i18n('ERROR'); } } } $thumb_exists = $thwidth = $thheight = $thtype = $athttr = ''; list($imgwidth, $imgheight, $imgtype, $imgattr) = getimagesize($src_folder . $subPath . $src); if (file_exists($thumb_folder . 'thumbnail.' . $src)) { list($thwidth, $thheight, $thtype, $athttr) = getimagesize($thumb_folder . 'thumbnail.' . $src); $thumb_exists = ' | <a href="' . $thumb_url . 'thumbnail.' . rawurlencode($src) . '" rel="fancybox_i" >' . i18n_r('CURRENT_THUMBNAIL') . '</a> <code>' . $thwidth . 'x' . $thheight . '</code>'; } else {
public function executeGenerate(sfWebRequest $request) { //data passes from index -> generate -> view. generate uses redirect at end. //hidden input field $this->generate_mosaic = $request->getPostParameter("generate"); if ($this->generate_mosaic == "1") { $base_path = "/var/www/symfony/web/uploads/"; //this is where the images go. $all_files = $request->getFiles(); $file = $all_files["image"]; $fname = $file["name"]; $fmime = $file["type"]; $ftmp = $file["tmp_name"]; //temp path $fsize = $file["size"]; $new_fname = uniqid(); //random name while (file_exists($base_path . $new_fname)) { $new_fname = uniqid(); } $img_path = $base_path . $new_fname; move_uploaded_file($ftmp, $img_path); //move image from temp path to uploads path. $img = ImageManipulation::imagecreatefrom($img_path); //see lib/image_lib.php. returns Image object. $img_width = imagesx($img); $img_height = imagesy($img); $img_ratio = $img_height / $img_width; $user_width = $request->getPostParameter("size"); //specified by user. $cell_sizes = array("small" => 5, "medium" => 15, "large" => 30); //user uses semantic descriptions (eg. "small"). if (array_key_exists($user_width, $cell_sizes)) { $cell_size = $cell_sizes[$user_width]; //match semantic user size with pixel value from $cell_sizes } else { $cell_size = $cell_sizes["medium"]; //default } $user_large_mosaic = $request->getPostParameter("large_mosaic"); //Checkbox for large mosaic $mosaic_width = 600; $mosaic_height = ceil($mosaic_width * $img_ratio); //Height adjusts to ratio. $new_img_width = $mosaic_width / $cell_size; //Image shrunk down so that later, $new_img_width * $cell_size = $mosaic_w $new_img_height = ceil($new_img_width * $img_ratio); $size_arr = getimagesize($img_path); //getimagesize() gets size from path; imagesx() gets size from Image object. ImageManipulation::resize_image($img_path, $img, $size_arr, $new_img_width, $new_img_height); //See lib/image_lib.php. No returns, resizes image. $keywords = $request->getPostParameter("keywords"); if (empty($keywords)) { $keywords = "cars"; //Default } $this->getUser()->setAttribute("img_path", $img_path); //Set Session variable. That way, if user refreshes, mosaic is still there. $this->getUser()->setAttribute("cell_size", $cell_size); //Same for cell sizes. $this->getUser()->setAttribute("keywords", $keywords); //Same for key } $this->redirect("/browse"); //on to view! }
<?php session_start(); $_SESSION["state"]++; $exp = ''; $ext = '.png'; if (isset($_POST['exp'])) { $exp = $_POST['exp']; } if ($exp == 'col') { $ext = '.jpg'; } $user_folder = 'images/temp/'; require 'inc/imagemanipulation.php'; $objImage = new ImageManipulation('images/Mosaic' . $exp . $ext); if ($objImage->imageok) { $objImage->setCrop($_POST['x'], $_POST['y'], $_POST['w'], $_POST['h']); if ($exp == 'col') { $objImage->save($user_folder . $_SESSION["id"] . $_SESSION["state"] . $ext); } else { $objImage->save($user_folder . $_SESSION["id"] . '_' . $_SESSION["state"] . $ext); } } else { echo 'Error!'; } $_SESSION["currentS"] = $_SESSION["state"]; if ($exp != 'col') { if ($_SESSION["piping"] == 99) { $text = ' <div class="item"> <h2>Cropped Image</h2>