function the_thumbnail($sizeW = 300, $sizeH = 300, $postid = null, $thumbnailid = null) { if ($postid == null) { $postid = get_the_ID(); } $size = array($sizeW, $sizeH); $post = get_post($postid); $thumbnailid = $thumbnailid == null ? get_post_thumbnail_id($post->ID) : $thumbnailid; $uri = wp_get_attachment_image_src($thumbnailid, 'full'); if (!$uri) { return placeholdit($sizeW, $sizeH); } $filename = explode('.', substr($uri[0], strrpos($uri[0], '/') + 1)); $extension = array_pop($filename); $title = implode('.', $filename); $upload_dir = wp_upload_dir(); $image_path = $upload_dir['path'] . '/' . $title . '-arpt-' . $size[0] . 'x' . $size[1] . '.' . $extension; $image_uri = $upload_dir['url'] . '/' . $title . '-arpt-' . $size[0] . 'x' . $size[1] . '.' . $extension; if (file_exists($image_path)) { return $image_uri; } $part_uri = explode(get_site_url(), $uri[0]); $the_url = ABSPATH . trim($part_uri[1], '/'); if (!file_exists($the_url)) { return placeholdit($sizeW, $sizeH); } try { $img = new abeautifulsite\SimpleImage($the_url); $img->thumbnail($size[0], $size[1]); $img->save($image_path); } catch (Exception $e) { return ''; } return $image_uri; }
public function reduceImage($routeDest) { $img = new \abeautifulsite\SimpleImage($this->route . $this->getFileName()); $img->fit_to_width(300); $img->save(); if ($routeDest) { $img->thumbnail(100, 75); $img->save($routeDest . $this->fileName); } }
public function insertPhotoEntry($data) { $albumId = $data['album']; $photoName = $data['name']; $path = JPATH_SITE . '/images/com_immotoa/' . $albumId; $info = pathinfo($photoName); $extension = $info['extension']; // get the extension of the file $filename = $info['filename']; // get the extension of the file if (!is_dir($path)) { mkdir($path); chmod($path, 0755); } include JPATH_SITE . '/vendor/autoload.php'; $img = new abeautifulsite\SimpleImage($data['file']); $img->auto_orient()->best_fit(2048, 2048); $img->save($path . '/' . $photoName, 90); return true; }
public function postUpdate($object) { // get controller $container = $this->getConfigurationPool()->getContainer(); $helper = $container->get('vich_uploader.templating.helper.uploader_helper'); // additional restauratn photo // set for photos restaurant foreach ($object->getAdditionalPhotos() as $additionalPhoto) { if (!is_null($additionalPhoto->getFile())) { $imagePath = $helper->asset($additionalPhoto, 'restaurant_additional_photo'); // check if file exist if (file_exists($imagePath)) { // get thumb image name $thumbImage = $additionalPhoto->getThumbFileName(); if (!is_null($thumbImage)) { $thumbPath = str_replace($additionalPhoto->getFileName(), $thumbImage, $imagePath); // create thumbnail $thumb = new \abeautifulsite\SimpleImage(getcwd() . $imagePath); $thumb->best_fit(RestaurantAdditionalPhoto::THUMB_HEIGHT, RestaurantAdditionalPhoto::THUMB_WIDTH)->save(getcwd() . $thumbPath); } } } } // menu photos foreach ($object->getAdditionalMenuPhotos() as $menuPhoto) { if (!is_null($menuPhoto->getFile())) { $imagePath = $helper->asset($menuPhoto, 'restaurant_menu_photo'); // check if file exist if (file_exists($imagePath)) { // get thumb image name $thumbImage = $menuPhoto->getThumbFileName(); if (!is_null($thumbImage)) { $thumbPath = str_replace($menuPhoto->getFileName(), $thumbImage, $imagePath); // create thumbnail $thumb = new \abeautifulsite\SimpleImage(getcwd() . $imagePath); $thumb->best_fit(RestaurantMenuPhoto::THUMB_HEIGHT, RestaurantMenuPhoto::THUMB_WIDTH)->save(getcwd() . $thumbPath); } } } } }
public function checkAddSmallProfileImage($profileImage) { $file = new File(); $file->Load('name = ?', array($profileImage->name . "_small")); if (empty($file->id)) { LogManager::getInstance()->info("Small profile image " . $profileImage->name . "_small not found"); $largeFileUrl = $this->getFileUrl($profileImage->name); $file->name = $profileImage->name . "_small"; $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; $file->{$signInMappingField} = $profileImage->{$signInMappingField}; $file->filename = $file->name . str_replace($profileImage->name, "", $profileImage->filename); $file->file_group = $profileImage->file_group; file_put_contents("/tmp/" . $file->filename . "_orig", file_get_contents($largeFileUrl)); if (file_exists("/tmp/" . $file->filename . "_orig")) { //Resize image to 100 $img = new abeautifulsite\SimpleImage("/tmp/" . $file->filename . "_orig"); $img->fit_to_width(100); $img->save("/tmp/" . $file->filename); $uploadFilesToS3Key = SettingsManager::getInstance()->getSetting("Files: Amazon S3 Key for File Upload"); $uploadFilesToS3Secret = SettingsManager::getInstance()->getSetting("Files: Amazone S3 Secret for File Upload"); $s3Bucket = SettingsManager::getInstance()->getSetting("Files: S3 Bucket"); $uploadname = CLIENT_NAME . "/" . $file->filename; $localFile = "/tmp/" . $file->filename; $s3FileSys = new S3FileSystem($uploadFilesToS3Key, $uploadFilesToS3Secret); $result = $s3FileSys->putObject($s3Bucket, $uploadname, $localFile, 'authenticated-read'); unlink("/tmp/" . $file->filename); unlink("/tmp/" . $file->filename . "_orig"); LogManager::getInstance()->info("Upload Result:" . print_r($result, true)); if (!empty($result)) { $ok = $file->Save(); } return $file; } return null; } return $file; }
} else { $output_dir = "../../img/slider/"; if (isset($_FILES["myfile"])) { $ret = array(); $error = $_FILES["myfile"]["error"]; //You need to handle both cases //If Any browser does not support serializing of multiple files using FormData() if (!is_array($_FILES["myfile"]["name"])) { $fileName = 'slider-' . rand(1000, 10000) . '.' . pathinfo($_FILES["myfile"]["name"], PATHINFO_EXTENSION); while (file_exists($output_dir . $fileName)) { $fileName = 'slider-' . rand(1000, 10000) . '.' . pathinfo($_FILES["myfile"]["name"], PATHINFO_EXTENSION); } if (move_uploaded_file($_FILES["myfile"]["tmp_name"], $output_dir . $fileName)) { mysql_query("INSERT INTO mainslider(path) VALUES ('{$fileName}')"); } $image = new abeautifulsite\SimpleImage($output_dir . $fileName); $image->fit_to_width(200)->save($output_dir . 'k-' . $fileName); $ret[] = $fileName; $ret[] = mysql_insert_id(); $ret[] = mysql_error(); } else { $fileCount = count($_FILES["myfile"]["name"]); for ($i = 0; $i < $fileCount; $i++) { $fileName = 'slider-' . rand(1000, 10000) . '.' . pathinfo($_FILES["myfile"]["name"], PATHINFO_EXTENSION); while (file_exists($output_dir . $fileName)) { $fileName = 'slider-' . rand(1000, 10000) . '.' . pathinfo($_FILES["myfile"]["name"], PATHINFO_EXTENSION); } if (move_uploaded_file($_FILES["myfile"]["tmp_name"], $output_dir . $fileName)) { mysql_query("INSERT INTO mainslider(path) VALUES ('{$fileName}')"); } $image = new SimpleImage();
public function createVersion($imagePath, $sizeString = false, $crop = true, $fitImageInCanvas = false) { if (strlen($this->urlAlias) < 1) { throw new \Exception('Image without urlAlias!'); } $cachePath = $this->getModule()->getCachePath(); $subDirPath = $this->getSubDur(); $fileExtension = pathinfo($this->filePath, PATHINFO_EXTENSION); if ($sizeString) { $sizePart = '_' . $sizeString; } else { $sizePart = ''; } $pathToSave = $cachePath . '/' . $subDirPath . '/' . $this->urlAlias . $sizePart . '.' . $fileExtension; BaseFileHelper::createDirectory(dirname($pathToSave), 0777, true); if ($sizeString) { $size = $this->getModule()->parseSize($sizeString); } else { $size = false; } if ($this->getModule()->graphicsLibrary == 'Imagick') { // Fixes interlaced images $interlaceFix = $this->interlaceFix($imagePath); if ($interlaceFix) { $image = new \Imagick(); $image->readImageBlob($interlaceFix); } else { $image = new \Imagick($imagePath); } $image->setImageCompressionQuality(100); // Fixes image rotations $this->ImagickAutoRotateImage($image); // If the dimensions of the original image match the requested // dimensions the original image is just copied to the new path if ($image->getImageWidth() == $size['width'] && $image->getImageHeight() == $size['height']) { copy($imagePath, $pathToSave); return $image; } if ($size) { if ($size['height'] && $size['width']) { if (!$crop && $fitImageInCanvas) { $image = $this->fitImageInCanvas($image, $size['width'], $size['height']); } elseif ($crop) { $image->cropThumbnailImage($size['width'], $size['height']); } else { $image->resizeImage($size['width'], $size['height'], \Imagick::FILTER_HAMMING, 1, false); } } elseif ($size['height']) { $image->thumbnailImage(0, $size['height']); } elseif ($size['width']) { $image->thumbnailImage($size['width'], 0); } else { throw new \Exception('Something wrong with this->module->parseSize($sizeString)'); } } $image->writeImage($pathToSave); } else { $image = new \abeautifulsite\SimpleImage($imagePath); // If the dimensions of the original image match the requested // dimensions the original image is just copied to the new path if ($image->get_width() == $size['width'] && $image->get_height() == $size['height']) { copy($imagePath, $pathToSave); return $image; } if ($size) { if ($size['height'] && $size['width']) { if ($crop) { $image->thumbnail($size['width'], $size['height']); } else { $image->resize($size['width'], $size['height']); } } elseif ($size['height']) { $image->fit_to_height($size['height']); } elseif ($size['width']) { $image->fit_to_width($size['width']); } else { throw new \Exception('Something wrong with this->module->parseSize($sizeString)'); } } //WaterMark if ($this->getModule()->waterMark) { if (!file_exists(Yii::getAlias($this->getModule()->waterMark))) { throw new Exception('WaterMark not detected!'); } $wmMaxWidth = intval($image->get_width() * 0.4); $wmMaxHeight = intval($image->get_height() * 0.4); $waterMarkPath = Yii::getAlias($this->getModule()->waterMark); $waterMark = new \abeautifulsite\SimpleImage($waterMarkPath); if ($waterMark->get_height() > $wmMaxHeight or $waterMark->get_width() > $wmMaxWidth) { $waterMarkPath = $this->getModule()->getCachePath() . DIRECTORY_SEPARATOR . pathinfo($this->getModule()->waterMark)['filename'] . $wmMaxWidth . 'x' . $wmMaxHeight . '.' . pathinfo($this->getModule()->waterMark)['extension']; //throw new Exception($waterMarkPath); if (!file_exists($waterMarkPath)) { $waterMark->fit_to_width($wmMaxWidth); $waterMark->save($waterMarkPath, 100); if (!file_exists($waterMarkPath)) { throw new Exception('Cant save watermark to ' . $waterMarkPath . '!!!'); } } } $image->overlay($waterMarkPath, 'bottom right', 0.5, -10, -10); } $image->save($pathToSave, 100); } return $image; }
<?php require_once "../../vendor/autoload.php"; $sourceImage = $_POST['sourceImage']; $watermark = $_POST['watermark']; $sourceK = $_POST['sourceK']; $watermarkK = $_POST['watermarkK']; $positionX = $_POST['x'] * $sourceK; $positionY = $_POST['y'] * $sourceK; $opacity = $_POST['opacity'] / 100; $mode = $_POST['mode']; $top = $_POST['top'] * $sourceK; $left = $_POST['left'] * $sourceK; $marginleft = $_POST['gutterLeft'] * $sourceK; $marginbottom = $_POST['gutterBottom'] * $sourceK; $image = new abeautifulsite\SimpleImage($sourceImage); $image_watermark = new abeautifulsite\SimpleImage($watermark); if ($watermarkK > 1) { $imgInfo = getimagesize($watermark); $newWidth = $imgInfo[0] / $watermarkK; $newHeight = $imgInfo[1] / $watermarkK; $image_watermark = $image_watermark->resize($newWidth, $newHeight); $image_watermark->save($watermark); } if ($mode == 'tiling') { $sourceSize = getimagesize($sourceImage); $watermarkSize = getimagesize($watermark); $sourceWidth = $sourceSize[0]; $sourceHeight = $sourceSize[1]; $offsetX = $left; //$data = $sourceWidth;
# Remove potential http:// if (strpos($src, 'http://') === 0) { $src = preg_replace('/http:\\/\\/(.*?)\\//', '/', $src); } # See if it's cached $cacheSrc = md5(implode($_GET)); $cacheSrc = 'cache/' . $cacheSrc . '.' . $ext; if (file_exists($cacheSrc)) { try { $img = new abeautifulsite\SimpleImage($cacheSrc); $img->output(); } catch (Exception $e) { echo $e->getMessage(); } die; } # OLD SIMPLE IMAGE CODE # Get the rest of the params TODO: Add all options: https://github.com/claviska/SimpleImage $blur = isset($_GET['blur']) ? $_GET['blur'] : false; # Run SimpleImage try { $img = new abeautifulsite\SimpleImage($docRoot . $src); # TODO: Add all options if ($blur > 0) { $img->blur('gaussian', $blur); } $img->save($cacheSrc); $img->output(); } catch (Exception $e) { echo $e->getMessage(); }
<?php include '../../application/libraries/SimpleImage.php'; $cat = 'tees/'; $oridir = "../jack/" . $cat; $files = array(); $dir = opendir($oridir); // open the cwd..also do an err check. while (false != ($file = readdir($dir))) { if ($file != "." and $file != ".." and $file != "index.php") { $files[] = $file; // put in array. } } natsort($files); // sort. // print. foreach ($files as $file) { $ori = $oridir . $file; // echo("<a href='$file'>$file</a> <br />\n"); try { $img = new abeautifulsite\SimpleImage($ori); $img->resize(460, 460)->save($cat . $file); } catch (Exception $e) { echo 'Error: ' . $e->getMessage(); } }
$mime = finfo_file($info, $tmpName); $acceptedMime = array("image/jpeg", "image/gif", "image/png"); if (!in_array($mime, $acceptedMime)) { $error = "Type de fichier refuser "; } if ($_FILES == $_SESSION['user']['pic_name']) { } if (empty($error)) { $extention = pathinfo($_FILES['pic_name']['name'], PATHINFO_EXTENSION); $pic_name = md5($tmpName . time() . uniqid()) . "." . $extention; $destinationDirectory = __DIR__ . "/../img/uploads/"; if (file_exists($destinationDirectory . "originals/" . $pic_name)) { $pic_name = md5($tmpName . time() . uniqid()) . uniqid() . "." . $extention; } move_uploaded_file($tmpName, $destinationDirectory . "originals/" . $pic_name); $img = new abeautifulsite\SimpleImage($destinationDirectory . "originals/" . $pic_name); $img->best_fit(600, 600)->save($destinationDirectory . "mediums/" . $pic_name); $img->thumbnail(150, 150)->save($destinationDirectory . "thumbnails/" . $pic_name); } if (empty($error)) { $sql = "UPDATE users \n\t\t\t\t\tSET pic_name = :pic_name\n\t\t\t\t\tWHERE id = :id"; $sth = $dbh->prepare($sql); $sth->bindValue(":id", $_SESSION['user']['id']); $sth->bindValue(':pic_name', $pic_name); $sth->execute(); $succes = "Modification enregistrer"; } } // insert dans la BDD if (empty($error)) { $sql = "UPDATE users \n\t\t\t\t\tSET user_name = :user_name, email = :email, bio = :bio\n\t\t\t\t\tWHERE id = :id";
$dimensions->fitWidthAndHeight($thumb->options['width'], $thumb->options['height'], $thumb->options['upscale']); $command[] = $dimensions->width() . 'x' . $dimensions->height() . '!'; } $command[] = '-quality ' . $thumb->options['quality']; if ($thumb->options['blur']) { $command[] = '-blur 0x' . $thumb->options['blurpx']; } $command[] = '"' . $thumb->destination->root . '"'; exec(implode(' ', $command)); }; /** * GDLib Driver */ thumb::$drivers['gd'] = function ($thumb) { try { $img = new abeautifulsite\SimpleImage($thumb->root()); $img->quality = $thumb->options['quality']; if ($thumb->options['crop']) { @$img->thumbnail($thumb->options['width'], $thumb->options['height']); } else { $dimensions = clone $thumb->source->dimensions(); $dimensions->fitWidthAndHeight($thumb->options['width'], $thumb->options['height'], $thumb->options['upscale']); @$img->resize($dimensions->width(), $dimensions->height()); } if ($thumb->options['grayscale']) { $img->desaturate(); } if ($thumb->options['blur']) { $img->blur('gaussian', $thumb->options['blurpx']); } if ($thumb->options['autoOrient']) {
$ter->lat = $_POST['lat']; $ter->lon = $_POST['lon']; $ter->opis = $_POST['opis']; $ter->insert(); header("Location: admin.php?id=2&cat=dodaj_teretanu.php"); } //dodavanje vezbe if (isset($_POST['dodaj_vezbu'])) { $vezba = new Vezbe(); $naziv = $_POST['naziv']; $search = array("?", ":", "ć", "Ć"); $replace = array("", "-", "c", "C"); $naziv = str_replace($search, $replace, $naziv); $output = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $naziv); $file_tmp = $_FILES['img']['tmp_name']; $img = new abeautifulsite\SimpleImage($file_tmp); $img->best_fit(500, 400)->mean_remove()->save("../images/vezbe/" . $output . ".jpg"); $vezba->naziv = $naziv; $vezba->tekst = $_POST['tekst']; $vezba->kategorija = $_POST['kategorije']; $vezba->insert(); header("Location: admin.php?id=2&cat=dodaj_vezbu.php"); } //dodavanje korisnika if (isset($_GET['dodajkorisnika'])) { $kor = new Users(); $kor->id = $_GET['dodajkorisnika']; $kor->status = "1"; $kor->update(); header("Location: admin.php?id=2"); }
//si accepté if (!in_array($mime, $acceptedMimes)) { $error = "Type de fichier refusé !"; } if (empty($error)) { //Nouveau nom du fichier sécuritaire $newName = md5($tmpName . time() . uniqid()) . "." . $ext; //chemin vers le répertoire où nous déplacerons l'image(4 underscores pour __DIR__) $destinationDirectory = __DIR__ . "/images/profils/"; //Si par hazard le fichier existe if (file_exists($destinationDirectory . $newName)) { $newName = md5($tmpName . time() . uniqid()) . uniqid() . "." . $ext; } //déplace le fichier temporaire vers un autre répretoire sur notre serveur move_uploaded_file($tmpName, $destinationDirectory . $newName); $img = new abeautifulsite\SimpleImage($destinationDirectory . $newName); //medium $img->best_fit(250, 200)->save($destinationDirectory . "mediums/" . $newName); //thumbnails $img->thumbnail(150, 150)->save($destinationDirectory . "thumbnails/" . $newName); //watermark //$img->overlay(__DIR__ . "/images/profils/", 'bottom right', .5, -10, -10)->save($destinationDirectory."originals/".$newName); if (!empty($_POST)) { $sql = "UPDATE users\n\t\t\tSET photo = :newName, profile_user = :profile_user\n\t\t\tWHERE email = :email"; $sth = $dbh->prepare($sql); $sth->bindValue(":email", $email); $sth->bindValue(":newName", $newName); $sth->bindValue(":profile_user", $profile_user); $sth->execute(); } } else {
public function profil() { $user = $this->getUser(); $userManager = new UserManager(); $error = ""; $succes = ""; $id = ""; $username = ""; $email = ""; $firstname = ""; $lastname = ""; $streetname = ""; $phonenumber = ""; $zipcode = ""; $pic_name = $this->getUser()['pic_name']; $user_name_regex = "/^[\\p{L}0-9._-]{2,100}\$/u"; if (!empty($_POST)) { $id = $user["id"]; $email = trim(strip_tags($_POST['email'])); $username = trim(strip_tags($_POST['username'])); $firstname = trim(strip_tags($_POST['firstname'])); $lastname = trim(strip_tags($_POST['lastname'])); $streetname = trim(strip_tags($_POST['streetname'])); $zipcode = trim(strip_tags($_POST['zipcode'])); $phonenumber = trim(strip_tags($_POST['phonenumber'])); //|||||||||||||||||||| username valide ? if (strlen($username) < 4) { $error = "Votre Pseudo doit comporter 4 lettres minimum !"; } if (!preg_match($user_name_regex, $username)) { $error = "Votre Pseudo ne doit pas contenir de caractère spéciaux !"; } else { if ($username !== $_SESSION['user']['username']) { $foundPseudo = $userManager->usernameExists($username); if (!empty($foundPseudo)) { $error = "Ce pseudo est déjà enregistré ici !"; } } } //|||||||||||||||| Email valide ? if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $error = "Email non valide"; } else { if ($email !== $_SESSION['user']['email']) { $foundEmail = $userManager->emailExists($email); if (!empty($foundEmail)) { $error = "Ce pseudo est déjà enregistré ici !"; } } } // |||||||||||||||| IMAGE valide ? if ($_FILES['pic_name']['error'] != 4) { $tmpName = $_FILES['pic_name']['tmp_name']; if ($_FILES['pic_name']['error'] != 0) { switch ($_FILES['pic_name']['error']) { case 1: $error = "Votre fichier est trop gros !"; break; case 4: $error = "Aucun fichier n'a été selectionné !"; break; default: $error = "Une erreur est survenue lors du chargement de votre image LOL"; break; } } $info = finfo_open(FILEINFO_MIME_TYPE); $mime = finfo_file($info, $tmpName); $acceptedMime = array("image/jpeg", "image/gif", "image/png"); if (!in_array($mime, $acceptedMime)) { $error = "Type de fichier refuser "; } if ($_FILES == $_SESSION['user']['pic_name']) { } if (empty($error)) { $extention = pathinfo($_FILES['pic_name']['name'], PATHINFO_EXTENSION); $pic_name = md5($tmpName . time() . uniqid()) . "." . $extention; $destinationDirectory = __DIR__ . "/../../public/assets/img/uploads/"; if (file_exists($destinationDirectory . "originals/" . $pic_name)) { $pic_name = md5($tmpName . time() . uniqid()) . uniqid() . "." . $extention; } move_uploaded_file($tmpName, $destinationDirectory . "originals/" . $pic_name); $img = new \abeautifulsite\SimpleImage($destinationDirectory . "originals/" . $pic_name); $img->best_fit(600, 600)->save($destinationDirectory . "mediums/" . $pic_name); $img->thumbnail(150, 150)->save($destinationDirectory . "thumbnails/" . $pic_name); } if (empty($error)) { $succes = "Bravo !"; } } //|||||||||||||||| ZIPCODE valide ? if ($zipcode <= "75000" || $zipcode >= "75021") { $error = "Vous devez habiter Paris pour vous inscrire à notre service !"; } //|||||||||||||||| Téléphone valide ? if (preg_match("/^[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}\$/", $phonenumber)) { // $phonenumber is valid $error = "Votre numéro de téléphone n'est pas valide !"; } //|||||||||||||||| 2er cihffre du Telephone coresponde a 01,02,03,04,05,06,07,08 ou 09 if (substr($phonenumber, 0, 2) < "01" || substr($phonenumber, 0, 2) > "09") { $error = "Votre numéro de téléphone n'est pas valide !"; } //si valide... if (empty($error)) { //insérer en base $modifySubscriber = ["username" => $username, "email" => $email, "firstname" => $firstname, "lastname" => $lastname, "zip_code" => $zipcode, "street_name" => $streetname, "phone_number" => $phonenumber, "date_modified" => date("Y-m-d H:i:s"), "pic_name" => $pic_name]; $userManager = new \Manager\UserManager(); $userManager->update($modifySubscriber, $id); //Crée une instance et refresh le contenu $am = new AuthentificationManager(); $am->refreshUser(); $succes = "Votre profil a bien été enregistré !"; } } $data = []; $data['error'] = $error; $data['succes'] = $succes; $data['username'] = $username; $data['email'] = $email; $data['firstname'] = $firstname; $data['lastname'] = $lastname; $data['zipcode'] = $zipcode; $data['streetname'] = $streetname; $data['phonenumber'] = $phonenumber; $data['pic_name'] = 'default.png'; $this->show('user/profile', $data); }
public function getColorImage() { $color = $_POST['color']; $this->load->helper('SimpleImage'); $finalImage = new abeautifulsite\SimpleImage(); $finalImage->create(100, 100, $color); echo $finalImage->output_base64('png'); }
function actionItems() { $path = $this->getPath(); $dir = opendir($path); $this->result->baseurl = $this->config->baseurl; $this->result->path = str_replace(realpath($this->root) . DIRECTORY_SEPARATOR, '', $this->getPath()); while ($file = readdir($dir)) { if ($file != '.' && $file != '..' && is_file($path . $file)) { $info = pathinfo($path . $file); if (!isset($info['extension']) or (!isset($this->config->extensions) or in_array(strtolower($info['extension']), $this->config->extensions))) { $item = array('file' => $file); if ($this->config->createThumb) { if (!is_dir($path . $this->config->thumbFolderName)) { mkdir($path . $this->config->thumbFolderName, 0777); } if (!file_exists($path . $this->config->thumbFolderName . DIRECTORY_SEPARATOR . $file)) { $img = new abeautifulsite\SimpleImage($path . $file); $img->best_fit(150, 150)->save($path . $this->config->thumbFolderName . DIRECTORY_SEPARATOR . $file, $this->config->quality); } $item['thumb'] = $this->config->thumbFolderName . DIRECTORY_SEPARATOR . $file; } $item['changed'] = date($this->config->datetimeFormat, filemtime($path . $file)); $item['size'] = $this->humanFilesize(filesize($path . $file)); $this->result->files[] = $item; } } } }
/** * Update Table Map */ public function editTableMapAction() { // get Current user $user = $this->container->get('security.context')->getToken()->getUser(); // Check if user auth in app if (!is_object($user) || !$user instanceof UserInterface) { throw new AccessDeniedException("Access denied"); } // collect data $tableMapId = $this->getRequest()->request->get('tableMapId'); $floor = $this->getRequest()->request->get('mapFloor'); $file = $this->getRequest()->files->get('mapFile'); $mapHall = $this->getRequest()->request->get('mapHall'); // init table Map $tableMap = $this->getTableMapManager()->findOneById($tableMapId); $tableMap->setFloor($floor); if (!is_null($mapHall)) { $tableMap->setHall($mapHall); } // Update file if isset if (!is_null($file)) { $tableMap->setFile($file); } $em = $this->getDoctrine()->getManager(); $em->persist($tableMap); $em->flush(); if (!is_null($file)) { // resize image $helper = $this->container->get('vich_uploader.templating.helper.uploader_helper'); $imagePath = getcwd() . $helper->asset($tableMap, 'table_map'); // check if file exist if (file_exists($imagePath) && getimagesize($imagePath)) { // resize (BIG versio) // Get bigImagePath $bigImagePath = str_replace($tableMap->getFileName(), $tableMap->getBigFileName(), $imagePath); $resizedBigImage = new \abeautifulsite\SimpleImage($imagePath); $resizedBigImage->resize(TableMap::IMAGE_WIDTH_BIG, TableMap::IMAGE_HEIGHT_BIG)->save($bigImagePath); $resizedImage = new \abeautifulsite\SimpleImage($imagePath); $resizedImage->resize(TableMap::IMAGE_WIDTH, TableMap::IMAGE_HEIGHT)->save($imagePath); } else { // delete entity // $em->remove($tableMap); // $em->flush(); } } return $this->redirect($this->generateUrl("table_viewCreateMap", array("restaurantId" => $tableMap->getRestaurant()->getId())) . "?mapId={$tableMapId}"); }
//проверяем, есть ли директория для загузки //if (!file_exists('../../files')){ // //если нет, то создаём\ // mkdir('./../files'.uploads,777); //} //создаём уникальное имя для файла $filename = md5(uniqid(rand(10000, 99999))); $filename_copy = $filename . '_copy'; $file_dist = $_SERVER["DOCUMENT_ROOT"] . uploads . $filename . '.' . $ftype; $file_copy_dist = $_SERVER["DOCUMENT_ROOT"] . uploads . $filename_copy . '.' . $ftype; $tmpname = $file['tmp_name']; if (!move_uploaded_file($tmpname, $file_dist)) { exit(createMessageJson(false, 'Ошибка при обработке файла изображения')); } //пока всё норм, далее конвертация $img = new abeautifulsite\SimpleImage(); $img->load($file_dist)->resize(172, 126)->save($file_copy_dist); unlink($file_dist); //запись в базу try { $database = new PDO('mysql:host=' . dbhost . ';dbname=' . dbname, dblogin, dbpassword); $qres = $database->prepare('insert into `projects` (`name`,`url`,`decsription`,`image`) values (:pname,:url,:description,:image)'); $qres->bindValue(':pname', $name, PDO::PARAM_STR); $qres->bindValue(':url', $url, PDO::PARAM_STR); $qres->bindValue(':description', $description, PDO::PARAM_STR); $qres->bindValue(':image', $filename_copy . '.' . $ftype, PDO::PARAM_STR); $qres->execute(); $database->NULL; } catch (PDOException $e) { //ошибка, $res = "Ошибка!: " . $e->getMessage();
/** * Resize and save an image * * @param * @return */ function resizeAndSaveImage($originalPath, $destination, $W, $H) { list($width, $height, $type, $attr) = getimagesize($originalPath); $img = new abeautifulsite\SimpleImage($originalPath); if ($width / $height < $W / $H) { //portrait $y1 = ($height * $W / $width - $H) / 2; $y2 = ($height * $W / $width - $H) / 2 + $H; $img->fit_to_width($W)->crop(0, $y1, $W, $y2)->save($destination); } else { //landscape $x1 = ($width * $H / $height - $W) / 2; $x2 = ($width * $H / $height - $W) / 2 + $W; $img->fit_to_height($H)->crop($x1, 0, $x2, $H)->save($destination); } /* if($width/$height < $W/$H){ $img->fit_to_width($W)->crop(0, ($height - $H) / 2, $W, (($height - $H) / 2) + $H)->save($destination); } else{ $img->fit_to_height($H)->crop(($width - $W) / 2, 0, (($width - $W) / 2) + $W, $H)->save($destination); } */ }
} } } if ($_FILES['file']['tmp_name']) { if ($_FILES['file']['error'] > 0) { $err['file'] = "An error has occurred"; } elseif ($_FILES["file"]["type"] != "image/gif" && $_FILES["file"]["type"] != "image/jpeg" && $_FILES["file"]["type"] != "image/pjpeg" && $_FILES["file"]["type"] != "image/png") { $err['file'] = "Invalid file type"; } } if (sizeof($err) == 0) { $sql = "update shoutUsers set fname = '{$first}', lname = '{$last}', email = '{$email}' where id = '{$_SESSION['uid']}'"; $result = mysqli_query($db, $sql) or die('Query failed: ' . mysqli_error($db)); if ($_FILES['file']['tmp_name']) { try { $img = new abeautifulsite\SimpleImage($_FILES['file']['tmp_name']); $img->fit_to_width(250)->save('photos/' . $_SESSION['uid'] . '.jpg'); $img->fit_to_width(800)->save('photos/lg_' . $_SESSION['uid'] . '.jpg'); } catch (Exception $e) { echo 'Error: ' . $e->getMessage(); } } $_SESSION['first'] = $first; $_SESSION['last'] = $last; header("Location: account.php?success=true"); exit; } else { header("Location: account.php?success=false1"); exit; } } elseif ($_POST['submit1']) {
function serve($width, $height, $person) { $app = \Slim\Slim::getInstance(); $response = $app->response(); $response['Content-Type'] = 'image/jpeg'; $img = new abeautifulsite\SimpleImage(getBestImage($width, $height, $person)); if ($img->get_width() / $img->get_height() >= $width / $height) { $img->fit_to_height($height); $centre = round($img->get_width() / 2); $x1 = $centre - $width / 2; $x2 = $centre + $width / 2; $img->crop($x1, 0, $x2, $height); } else { $img->fit_to_width($width); $centre = round($img->get_height() / 2); $y1 = $centre - $height / 2; $y2 = $centre + $height / 2; $img->crop(0, $y1, $width, $y2); } $img = applyFilters($img); $img->output(); }
private function upload($id) { if (isset($this->request->data['foto']) and count($this->request->data['foto']) > 0 and $this->request->data['foto']['name'] != '') { $file = new File($this->request->data['foto']['tmp_name'], true, 0644); $ext = explode('/', $this->request->data['foto']['type']); $file->copy(ROOT . DS . 'webroot' . DS . 'ImagemProdutos' . DS . $id . '.' . strtolower($ext[1])); $file->close(); try { $img = new \abeautifulsite\SimpleImage(ROOT . DS . 'webroot' . DS . 'ImagemProdutos' . DS . $id . '.' . strtolower($ext[1])); $img->auto_orient()->best_fit(500, 500)->save(ROOT . DS . 'webroot' . DS . 'ImagemProdutos' . DS . $id . '.' . strtolower($ext[1])); } catch (Exception $e) { echo 'Error: ' . $e->getMessage(); } return $id . '.' . strtolower($ext[1]); } else { return null; } }
public function save() { $eqApp = new Apps(); $getFinfo_q = 'SELECT * FROM cms_records WHERE fieldsetid = "' . $_POST['fieldsetid'] . '" ORDER BY sortorder ASC'; $getFinfo_r = mysql_query($getFinfo_q); $getFinfo_n = mysql_num_rows($getFinfo_r); $pnum = 1; $checkPosted = 0; //START INSERT QUERY BEGINNING WITH USUAL STARTING VALUES $query_q = 'UPDATE cms_content SET '; //WHILE LOOP FOR ADDING THE DATABASE VALUES while ($getFinfo = mysql_fetch_array($getFinfo_r)) { switch ($getFinfo['type']) { case "file": if (isset($_FILES[$_POST['recordset'] . '_' . $getFinfo['db_name']]["name"])) { $fileInput = rand() . $_FILES[$_POST['recordset'] . '_' . $getFinfo['db_name']]["name"]; if (!file_exists('../uploads/' . $_POST['id'] . '/')) { mkdir('../uploads/' . $_POST['id'] . '/', 0777); } if (!file_exists('../uploads/' . $_POST['id'] . '/' . $getFinfo['db_name'])) { mkdir('../uploads/' . $_POST['id'] . '/' . $getFinfo['db_name'], 0777); } else { foreach (glob('../uploads/' . $_POST['id'] . '/' . $getFinfo['db_name'] . '/*') as $file) { if (is_dir($file)) { recursiveRemoveDirectory($file); } else { unlink($file); } } } move_uploaded_file($_FILES[$_POST['recordset'] . '_' . $getFinfo['db_name']]["tmp_name"], '../uploads/' . $_POST['id'] . '/' . $getFinfo['db_name'] . '/' . $filename . '.' . $fileext); $query_q .= ($pnum > 1 ? ", " : " ") . $getFinfo['db_name'] . '="' . $fileInput . '" '; $checkPosted++; } break; case "photo": if (!empty($_FILES[$_POST['recordset'] . '_' . $getFinfo['db_name']]["name"])) { if (!file_exists('../uploads/' . $_POST['id'] . '/')) { mkdir('../uploads/' . $_POST['id'] . '/', 0777); } if (!file_exists('../uploads/' . $_POST['id'] . '/' . $getFinfo['db_name'])) { mkdir('../uploads/' . $_POST['id'] . '/' . $getFinfo['db_name'], 0777); } else { foreach (glob('../uploads/' . $_POST['id'] . '/' . $getFinfo['db_name'] . '/*') as $file) { if (is_dir($file)) { recursiveRemoveDirectory($file); } else { unlink($file); } } } $filename = pathinfo($_FILES[$_POST['recordset'] . '_' . $getFinfo['db_name']]["name"], PATHINFO_FILENAME); $fileext = strtolower(pathinfo($_FILES[$_POST['recordset'] . '_' . $getFinfo['db_name']]["name"], PATHINFO_EXTENSION)); $filename = strtolower(rand() . $filename); $img = new abeautifulsite\SimpleImage($_FILES[$_POST['recordset'] . '_' . $getFinfo['db_name']]['tmp_name']); $img->fit_to_width(300)->save('../uploads/' . $_POST['id'] . '/' . $getFinfo['db_name'] . '/300xauto_' . $filename . '.' . $fileext); $img->save('../uploads/' . $_POST['id'] . '/' . $getFinfo['db_name'] . '/' . $filename . '.' . $fileext); move_uploaded_file($_FILES[$_POST['recordset'] . '_' . $getFinfo['db_name']]["tmp_name"], '../uploads/' . $_POST['id'] . '/' . $getFinfo['db_name'] . '/' . $filename . '.' . $fileext); $query_q .= ($pnum > 1 ? ", " : " ") . $getFinfo['db_name'] . '="' . $filename . '.' . $fileext . '" '; $checkPosted++; } break; case "html": $query_q .= ($pnum > 1 ? ", " : " ") . $getFinfo['db_name'] . '="' . addslashes(htmlspecialchars($_POST[$_POST['recordset'] . '_' . $getFinfo['db_name']])) . '" '; $checkPosted++; break; case "yesno": $query_q .= ($pnum > 1 ? ", " : " ") . $getFinfo['db_name'] . '="' . $_POST[$_POST['recordset'] . '_' . $getFinfo['db_name']] . '" '; $checkPosted++; break; case "multiselect": case "checkboxes": $vals = ""; $x = 0; if (isset($_POST[$_POST['recordset'] . '_' . $getFinfo['db_name']])) { foreach ($_POST[$_POST['recordset'] . '_' . $getFinfo['db_name']] as $key => $value) { $x++; $vals .= $value . ($x < count($_POST[$_POST['recordset'] . '_' . $getFinfo['db_name']]) ? "," : ""); } $query_q .= ($pnum > 1 ? ", " : " ") . $getFinfo['db_name'] . '="' . $vals . '" '; $checkPosted++; } break; case "radio": $vals = ""; $x = 0; if (!empty($_POST[$_POST['recordset'] . '_' . $getFinfo['db_name']])) { $query_q .= ($pnum > 1 ? ", " : " ") . $getFinfo['db_name'] . '="' . htmlspecialchars($_POST[$_POST['recordset'] . '_' . $getFinfo['db_name']]) . '" '; $checkPosted++; } break; case "foreignkey": $fkeyOptions = $eqApp->get_field_options($getFinfo['options'], $pnum - 1); if ($fkeyOptions['record_fkeytype'] == "select") { $query_q .= ($pnum > 1 ? ", " : " ") . $getFinfo['db_name'] . '="' . htmlspecialchars($_POST[$_POST['recordset'] . '_' . $getFinfo['db_name']]) . '" '; $checkPosted++; } elseif ($fkeyOptions['record_fkeytype'] == "multiselect") { $vals = ''; if (isset($_POST[$_POST['recordset'] . '_' . $getFinfo['db_name']])) { $d = 0; foreach ($_POST[$_POST['recordset'] . '_' . $getFinfo['db_name']] as $key => $value) { $d++; $vals .= htmlspecialchars($value) . ($d < count($_POST[$_POST['recordset'] . '_' . $getFinfo['db_name']]) ? "," : ""); } } $query_q .= ($pnum > 1 ? ", " : " ") . $getFinfo['db_name'] . '="' . $vals . '" '; $checkPosted++; } break; case "custom_url": $custom_url = ltrim(rtrim($getFinfo['custom_url'], '/'), '/'); $perma = explode('/', $custom_url); $postedCustomUrl = ""; $ddnum = 0; foreach ($perma as $links) { $ddnum++; if (isset($_POST[$links])) { $postedCustomUrl .= $eqApp->permaLink($_POST[$links]) . '/'; } } $postedCustomUrl = rtrim($postedCustomUrl, '/'); $checkCU_q = 'SELECT * FROM cms_content WHERE custom_url = "' . $postedCustomUrl . '" AND id <> "' . $_POST['id'] . '"'; $checkCU_r = mysql_query($checkCU_q); $query_q .= ($pnum > 1 ? ", " : " ") . $getFinfo['db_name'] . '="' . $postedCustomUrl . (mysql_num_rows($checkCU_r) > 0 ? rand() : '') . '" '; $checkPosted++; break; default: //for text,textarea,colorpicker,date,select $query_q .= ($pnum > 1 ? ", " : " ") . $getFinfo['db_name'] . '="' . htmlspecialchars($_POST[$_POST['recordset'] . '_' . $getFinfo['db_name']]) . '" '; $checkPosted++; break; } $pnum++; } $query_q .= 'WHERE id = "' . $_POST['id'] . '"'; if ($checkPosted > 0) { mysql_query($query_q) or die(mysql_error()); } exit; }
private function resize() { require 'SimpleImage.php'; $path = DEF_IMG_UP_DIR . USER_ID . DS . $this->name . '.' . $this->ext; $t_path = DEF_IMG_UP_DIR . USER_ID . '/thumbnails'; if (!is_dir($t_path)) { mkdir($t_path); } $t_path = DEF_IMG_UP_DIR . USER_ID . '/thumbnails/' . $this->name . '.' . $this->ext; $img = new abeautifulsite\SimpleImage($path); $img->thumbnail(120, 120)->save($t_path); }
$db = new DbHandler(); $user = $db->getUserByUserId($user_id); if ($user != NULL && $user['isAdmin']) { for ($i = 0; $i < count($_FILES['files']['name']); $i++) { //Get the temp file path $tmpFilePath = $_FILES['files']['tmp_name'][$i]; //Make sure we have a filepath if ($tmpFilePath != "") { //Setup our new file path $name = $_FILES['files']['name'][$i]; $name = str_replace(" ", "_", $name); $newFilePath = rand(1, 100000) . $value . "_" . $name; //Upload the file into the temp dir if (move_uploaded_file($tmpFilePath, "../images/" . $newFilePath)) { try { $img = new abeautifulsite\SimpleImage("../images/" . $newFilePath); $img->thumbnail(160, 160)->save("../images/thumb/" . $newFilePath); $result = "ok"; $res = $db->saveImageByProductId($product_id, $newFilePath); } catch (Exception $e) { $result = 'Error: ' . $e->getMessage(); } //Handle other code here } } } /*$result = $_FILES['files'];*/ $response["error"] = false; $response["result"] = $result; echoRespnse(200, $response); } else {
public function createVersion($imagePath, $sizeString = false) { if (strlen($this->urlAlias) < 1) { throw new \Exception('Image without urlAlias!'); } $cachePath = $this->getModule()->getCachePath(); $subDirPath = $this->getSubDur(); $fileExtension = pathinfo($this->filePath, PATHINFO_EXTENSION); if ($sizeString) { $sizePart = '_' . $sizeString; } else { $sizePart = ''; } $pathToSave = $cachePath . '/' . $subDirPath . '/' . $this->urlAlias . $sizePart . '.' . $fileExtension; BaseFileHelper::createDirectory(dirname($pathToSave), 0777, true); if ($sizeString) { $size = $this->getModule()->parseSize($sizeString); } else { $size = false; } if ($this->getModule()->graphicsLibrary == 'Imagick') { $image = new \Imagick($imagePath); $image->setImageCompressionQuality(100); if ($size) { if ($size['height'] && $size['width']) { $image->cropThumbnailImage($size['width'], $size['height']); } elseif ($size['height']) { $image->thumbnailImage(0, $size['height']); } elseif ($size['width']) { $image->thumbnailImage($size['width'], 0); } else { throw new \Exception('Something wrong with this->module->parseSize($sizeString)'); } } $image->writeImage($pathToSave); } else { $image = new \abeautifulsite\SimpleImage($imagePath); if ($size) { if ($size['height'] && $size['width']) { //$image->thumbnail($size['width'], $size['height']); $image->best_fit($size['width'], $size['height']); } elseif ($size['height']) { $image->fit_to_height($size['height']); } elseif ($size['width']) { $image->fit_to_width($size['width']); } else { throw new \Exception('Something wrong with this->module->parseSize($sizeString)'); } } //WaterMark if ($this->getModule()->waterMark) { if (!file_exists(Yii::getAlias($this->getModule()->waterMark))) { throw new Exception('WaterMark not detected!'); } $wmMaxWidth = intval($image->get_width() * 0.4); $wmMaxHeight = intval($image->get_height() * 0.4); $waterMarkPath = Yii::getAlias($this->getModule()->waterMark); $waterMark = new \abeautifulsite\SimpleImage($waterMarkPath); if ($waterMark->get_height() > $wmMaxHeight or $waterMark->get_width() > $wmMaxWidth) { $waterMarkPath = $this->getModule()->getCachePath() . DIRECTORY_SEPARATOR . pathinfo($this->getModule()->waterMark)['filename'] . $wmMaxWidth . 'x' . $wmMaxHeight . '.' . pathinfo($this->getModule()->waterMark)['extension']; //throw new Exception($waterMarkPath); if (!file_exists($waterMarkPath)) { $waterMark->fit_to_width($wmMaxWidth); $waterMark->save($waterMarkPath, 100); if (!file_exists($waterMarkPath)) { throw new Exception('Cant save watermark to ' . $waterMarkPath . '!!!'); } } } $image->overlay($waterMarkPath, 'bottom right', 0.5, -10, -10); } $image->save($pathToSave, 100); } return $image; }
private function save_action_image($new_file_name) { ini_set('memory_limit', '256M'); include './third_part/SimpleImage.php'; try { $img = new abeautifulsite\SimpleImage($this->user_action_uploads_dir . $new_file_name); $wim = $img->get_width(); $him = $img->get_height(); if ($wim > 1000 && $him > 250) { $img->fit_to_width(740)->save($this->user_action_save_dir . '740_' . $new_file_name); $img->fit_to_width(200)->save($this->user_action_save_dir . '200_' . $new_file_name); if (file_exists($this->user_action_save_dir . '740_' . $new_file_name) && file_exists($this->user_action_save_dir . '200_' . $new_file_name)) { unlink($this->user_action_uploads_dir . $new_file_name); echo json_encode(array('file_name' => $new_file_name, "success" => 1)); } else { echo json_encode(array("error" => -1, 'error_message' => 'unknown_file')); } } else { unlink($this->user_action_uploads_dir . $new_file_name); echo json_encode(array("error" => -1, 'error_message' => 'size_error')); } } catch (Exception $e) { echo json_encode(array("error" => -1, 'error_message' => $e->getMessage())); } }