Exemple #1
1
function imageWatermarking($soure, $target)
{
    $imagine = new Imagine\Gd\Imagine();
    $watermark = $imagine->open('./img/watermark.png');
    $image = $imagine->open($soure);
    $size = $image->getSize();
    $wSize = $watermark->getSize();
    $bottomRight = new Imagine\Image\Point(($size->getWidth() - $wSize->getWidth()) / 2, $size->getHeight() - $wSize->getHeight());
    $image->paste($watermark, $bottomRight);
    $image->save($target);
}
 public function generateThumbnail()
 {
     @ini_set('memory_limit', '256M');
     $source = $this->source;
     if (!$source || $source->isNew()) {
         return false;
     }
     try {
         $x = isset($this->_thumbnail_size['x']) ? $this->_thumbnail_size['x'] : 0;
         $y = isset($this->_thumbnail_size['y']) ? $this->_thumbnail_size['y'] : 0;
         if (!$x && !$y) {
             return false;
         }
         $imagine = new \Imagine\Gd\Imagine();
         $image = $imagine->open($source->fullpath);
         if ($x && $y) {
             $size = new \Imagine\Image\Box($x, $y);
         } else {
             $image_size = $image->getSize();
             $larger = max($image_size->getWidth(), $image_size->getHeight());
             $scale = max($x, $y);
             $size = $image_size->scale(1 / ($larger / $scale));
         }
         $thumbnail = $image->thumbnail($size, \Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND);
         $string = sprintf('data:image/png;base64,%s', base64_encode((string) $thumbnail));
         return $string;
     } catch (Exception $e) {
         return false;
     }
 }
 public function uploadAction($folder)
 {
     $file = \Input::file('file');
     $destinationPath = public_path() . '/uploads/assets/' . $folder;
     $thumbDestinationPath = public_path() . '/uploads/assets/thumbs/' . $folder;
     if (!is_dir($destinationPath)) {
         mkdir($destinationPath);
     }
     if (!is_dir($thumbDestinationPath)) {
         mkdir($thumbDestinationPath);
     }
     $filename = $file->getClientOriginalName();
     $upload_success = $file->move($destinationPath, $filename);
     @chmod($thumbDestinationPath, 0777);
     @chmod($destinationPath, 0777);
     @chmod($destinationPath . '/' . $filename, 0777);
     $attributes = ['folder_id' => $folder, 'filename' => $filename, 'filepath' => '/uploads/assets/' . $folder, 'filetype' => AssetsFile::getFileType($file->getClientMimeType())];
     $assetFile = AssetsFile::updateOrCreate($attributes, $attributes);
     if ($assetFile->filetype == AssetsFile::FILETYPE_IMAGE) {
         $imagine = new \Imagine\Gd\Imagine();
         $imagine->open($destinationPath . '/' . $filename)->thumbnail(new Box(200, 200), \Imagine\Image\ImageInterface::THUMBNAIL_INSET)->save($thumbDestinationPath . '/' . $filename);
     }
     if ($upload_success) {
         return \Response::json(['file' => $assetFile->toArray()], 200);
     } else {
         return \Response::json('error', 400);
     }
 }
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $builder->add('image', 'file', ['label' => false, 'attr' => ['title' => 'Choose a file to upload', 'class' => "btn btn-info btn-sm", 'accept' => '.jpg,.png,.gif|image/jpeg|image/png|image/gif'], 'constraints' => [new Assert\NotBlank(['message' => 'Please add an image'])], 'required' => true])->add('x', 'hidden', ['mapped' => false])->add('y', 'hidden', ['mapped' => false])->add('w', 'hidden', ['mapped' => false])->add('h', 'hidden', ['mapped' => false])->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
         $form = $event->getForm();
         $file = $form->get('image')->getData();
         $x = $form->get('x')->getData();
         $y = $form->get('y')->getData();
         $w = $form->get('w')->getData();
         $h = $form->get('h')->getData();
         if ($file) {
             $path = $file->getRealPath();
             $this->fixImageOrientation($path);
             if ($w && $h) {
                 try {
                     $imagine = new \Imagine\Gd\Imagine();
                     $original = $imagine->open($path);
                     $cropPoint = new \Imagine\Image\Point($x, $y);
                     $tmpPath = $path . '.' . $file->guessExtension();
                     $original->crop($cropPoint, new \Imagine\Image\Box($w, $h))->save($tmpPath);
                     file_put_contents($path, file_get_contents($tmpPath));
                     unlink($tmpPath);
                 } catch (\Imagine\Exception\RuntimeException $exception) {
                     //nothing to do
                 }
             }
         }
     });
 }
Exemple #5
0
 /**
  * Creates a set of files from the initial data and returns them as key/value
  * pairs, where the path on disk maps to name which each file should have.
  * Example:
  *
  *   [
  *     '/tmp/path/to/file/on/disk' => 'file.pdf',
  *     '/tmp/path/to/file/on/disk-2' => 'file-preview.png',
  *   ]
  *
  * @return array key/value pairs of temp files mapping to their names
  */
 public function transform()
 {
     // Get uploaded image from tmp directory
     $imagine = new \Imagine\Gd\Imagine();
     $image = $imagine->open($this->data['tmp_name']);
     // Get path to tmp directory
     $tmpPathParts = explode(DS, $this->data['tmp_name']);
     array_pop($tmpPathParts);
     // remove filename from path
     $tmpPath = implode(DS, $tmpPathParts);
     // Process fullsize image
     if ($this->isTooBig($image)) {
         // Shrink image to max dimensions and save in tmp dir
         $size = new \Imagine\Image\Box(2000, 2000);
         $mode = \Imagine\Image\ImageInterface::THUMBNAIL_INSET;
         $tmpFullsize = microtime() . $this->data['name'];
         $image->thumbnail($size, $mode)->save($tmpPath . DS . $tmpFullsize);
         $retval[$tmpPath . DS . $tmpFullsize] = $this->data['name'];
     } else {
         $retval[$this->data['tmp_name']] = $this->data['name'];
     }
     // Create thumbnail
     $size = new \Imagine\Image\Box(200, 200);
     $mode = \Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND;
     $thumbFilename = $this->generateThumbnailFilename($this->data['name']);
     $image->thumbnail($size, $mode)->save($tmpPath . DS . $thumbFilename);
     $retval[$tmpPath . DS . $thumbFilename] = $thumbFilename;
     return $retval;
 }
Exemple #6
0
 public function generateThumbnail()
 {
     @ini_set('memory_limit', '256M');
     if (($source = $this->getSource()) && $this->_canGenerate()) {
         try {
             $imagine = new \Imagine\Gd\Imagine();
             $image = $imagine->open($source->fullpath);
             $size = $this->getSize();
             if ($size['x'] && $size['y']) {
                 $size = new \Imagine\Image\Box($size['x'], $size['y']);
             } else {
                 $image_size = $image->getSize();
                 $larger = max($image_size->getWidth(), $image_size->getHeight());
                 $scale = max($size['x'], $size['y']);
                 $size = $image_size->scale(1 / ($larger / $scale));
             }
             $string = (string) $image->thumbnail($size, \Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND);
             $string = sprintf('data:%s;base64,%s', $source->mimetype, base64_encode($string));
             return $string;
         } catch (Exception $e) {
             return false;
         }
     }
     return false;
 }
 function resize($source, $path, $fileName, $maxWidth = null, $maxHeight = null)
 {
     $imagine = new Imagine\Gd\Imagine($source);
     $image = $imagine->open($source);
     $imageSize = $image->getSize();
     if ($maxWidth || $maxHeight) {
         if (!$maxHeight && $imageSize->getWidth() > $maxWidth) {
             $image->resize($imageSize->widen($maxWidth));
         } elseif (!$maxWidth && $imageSize->getHeight() > $maxHeight) {
             $image->resize($imageSize->heighten($maxHeight));
         } elseif ($maxWidth && $maxHeight) {
             if ($imageSize->getWidth() > $imageSize->getHeight()) {
                 $image->resize($imageSize->widen($maxWidth));
                 if ($imageSize->getHeight() > $maxHeight) {
                     $image->resize($imageSize->heighten($maxHeight));
                 }
             } else {
                 $image->resize($imageSize->heighten($maxHeight));
                 if ($imageSize->getWidth() > $maxWidth) {
                     $image->resize($imageSize->widen($maxWidth));
                 }
             }
             //$image->resize(new Box($maxWidth, $maxHeight));
         }
     }
     $this->makePath($path);
     $image->save($path . '/' . $fileName);
 }
Exemple #8
0
 public function image()
 {
     $imagine = new Imagine\Gd\Imagine();
     $image = $imagine->open('example.png');
     $thumbnail = $image->thumbnail(new Imagine\Image\Box(100, 100));
     $thumbnail->save('example.thumb.png');
 }
 /**
  * Resize a file uploaded
  * @param  string   $path   Path of the data, for instance to upload the file in data['Movie']['picture'] path would be Movie.picture
  * @param  string   $dest   Where to save the uploaded file
  * @param  integer  $width
  * @param  integer  $height
  * @return boolean  True if the image is uploaded.
  */
 public function move($path, $dest, $width = 0, $height = 0)
 {
     $file = Hash::get($this->controller->request->data, $path);
     if (empty($file['tmp_name'])) {
         return false;
     }
     $tmp = TMP . $file['name'];
     move_uploaded_file($file['tmp_name'], $tmp);
     $info = pathinfo($file['name']);
     $destinfo = pathinfo($dest);
     $directory = dirname(IMAGES . $dest);
     if (!file_exists($directory)) {
         mkdir($directory, 0777, true);
     }
     if ($info['extension'] == $destinfo['extension'] && $width == 0) {
         rename($tmp, IMAGES . $dest);
         return true;
     }
     if (!file_exists($dest_file)) {
         require_once APP . 'Plugin' . DS . 'Media' . DS . 'Vendor' . DS . 'imagine.phar';
         $imagine = new Imagine\Gd\Imagine();
         $imagine->open($tmp)->thumbnail(new Imagine\Image\Box($width, $height), Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND)->save(IMAGES . $dest, array('quality' => 90));
     }
     return true;
 }
Exemple #10
0
 /**
  * Generate a thumb of an image and save it to the specific path.
  *
  * @param string $sourceFile
  * @param string $destFile
  * @param boolean $isCloud
  * @return boolean
  */
 public function thumb($sourceFile, $destFile, $isCloud = false, $cloudFileName = '')
 {
     if (!file_exists($sourceFile)) {
         return false;
     }
     if (file_exists($destFile)) {
         unlink($destFile);
     }
     $size = new \Imagine\Image\Box(self::THUMB_WIDTH, self::THUMB_HEIGHT);
     $mode = \Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND;
     try {
         $this->_imagine->open($sourceFile)->thumbnail($size, $mode)->save($destFile);
     } catch (Exception $e) {
         return false;
     }
     // Save to cloud
     if ($isCloud) {
         Manager_File_Rackspace::getInstance()->saveFile($destFile, $cloudFileName, false, 'image/jpeg');
     }
     return true;
 }
Exemple #11
0
 public function resizeAction()
 {
     $conf = $this->getDI()->get('config');
     $tmpDir = $conf->application->tmpDir;
     $tmpImgDir = $conf->application->tmpDir . "images/";
     if (!is_dir($tmpDir)) {
         mkdir($tmpDir, 0777, true);
     }
     if (!is_dir($tmpImgDir)) {
         mkdir($tmpImgDir, 0777, true);
     }
     $imgUrl = $this->request->getPost('img_url');
     $productUrl = $this->request->getPost('product_from_url');
     if (empty($imgUrl) || empty($productUrl)) {
         $this->flashJson(500, array(), "非法请求");
         exit;
     }
     // $imgUrl = 'http://img11.360buyimg.com/n1/g14/M00/10/1F/rBEhVlMDOEMIAAAAAASiVlD7TXwAAIz3gAp0kUABKJu998.jpg';
     // $productUrl = 'http://item.jd.com/1082070511.html';
     $imagine = new \Imagine\Gd\Imagine();
     $image = $imagine->open($imgUrl);
     $mode = \Imagine\Image\ImageInterface::THUMBNAIL_INSET;
     $filename = $this->createGuid('image');
     $extname = pathinfo($imgUrl, PATHINFO_EXTENSION);
     $imageUrls = array();
     foreach (array(0, 75, 150, 300) as $width) {
         $objName = '/' . $filename . '_' . $width . '.' . $extname;
         $filePath = $tmpImgDir . $objName;
         if ($width == 0) {
             $image->save($filePath);
         } else {
             $size = new \Imagine\Image\Box($width, $width);
             $image->thumbnail($size, $mode)->save($filePath, array('quality' => 100));
         }
         $imageUrls[$objName] = $filePath;
     }
     if ($this->upload($imageUrls)) {
         $imageModel = new ImageModel();
         $imageModel->product_from_url = $productUrl;
         $imageModel->name = $filename;
         $imageModel->extname = $extname;
         $imageModel->url_prefix = 'http://bcs.duapp.com/' . $conf->bcs->bucket . '/';
         if ($imageModel->save() == false) {
             foreach ($imageModel->getMessages() as $message) {
                 echo $message->__toString();
             }
         }
         $this->flashJson(200, array('filename' => $filename));
     } else {
         $this->flashJson(500, array(), "抱歉,文件上传失败,请重试!");
     }
     exit;
 }
Exemple #12
0
 /**
  * Resize an image
  * @param  string  $url
  * @param  integer $width
  * @param  integer $height
  * @param  boolean $crop
  * @return string
  */
 public function resize($url, $width = 100, $height = null, $crop = false, $quality = 90)
 {
     if ($url) {
         // URL info
         $info = pathinfo($url);
         // The size
         if (!$height) {
             $height = $width;
         }
         // Quality
         $quality = Config::get('redminportal::image.quality', $quality);
         // Directories and file names
         $fileName = $info['basename'];
         $sourceDirPath = public_path() . '/' . $info['dirname'];
         $sourceFilePath = $sourceDirPath . '/' . $fileName;
         $targetDirName = $width . 'x' . $height . ($crop ? '_crop' : '');
         $targetDirPath = $sourceDirPath . '/' . $targetDirName . '/';
         $targetFilePath = $targetDirPath . $fileName;
         $targetUrl = asset($info['dirname'] . '/' . $targetDirName . '/' . $fileName);
         // Create directory if missing
         try {
             // Create dir if missing
             if (!Filesystem::isDirectory($targetDirPath) and $targetDirPath) {
                 @Filesystem::makeDirectory($targetDirPath);
             }
             // Set the size
             $size = new Box($width, $height);
             // Now the mode
             $mode = $crop ? ImageInterface::THUMBNAIL_OUTBOUND : ImageInterface::THUMBNAIL_INSET;
             if (!Filesystem::exists($targetFilePath) or Filesystem::lastModified($targetFilePath) < Filesystem::lastModified($sourceFilePath)) {
                 $this->imagine->open($sourceFilePath)->thumbnail($size, $mode)->save($targetFilePath, array('quality' => $quality));
             }
         } catch (\Exception $e) {
             Log::error('[IMAGE SERVICE] Failed to resize image "' . $url . '" [' . $e->getMessage() . ']');
         }
         return $targetUrl;
     }
 }
Exemple #13
0
 public function upload($id)
 {
     if ($this->validate()) {
         mkdir("../web/images/arenda/" . $id, 0777);
         foreach ($this->imageFiles as $file) {
             $filename = md5($file->baseName . date('Ymdhis'));
             $imagine = new \Imagine\Gd\Imagine();
             $watermark = $imagine->open('../web/images/arenda/water.png ');
             $image = $imagine->open($file->tempName);
             $size = $image->getSize();
             $wSize = $watermark->getSize();
             $bottomRight = new \Imagine\Image\Point($size->getWidth() - $wSize->getWidth(), $size->getHeight() - $wSize->getHeight());
             $image->paste($watermark, $bottomRight)->save('../web/images/arenda/' . $id . '/' . $filename . '.' . $file->extension);
             $model = new ImagesForAds();
             $model->ad_id = $id;
             $model->image_url = $filename . '.' . $file->extension;
             $model->save();
         }
         return true;
     } else {
         return false;
     }
 }
 public static function thumb(\KSPM\LCMS\Model\AssetsFile $file)
 {
     $dirPath = public_path() . '/' . $file->filepath;
     $destPath = public_path() . '/uploads/assets/thumbs/' . $file->folder_id;
     if (!file_exists($dirPath . '/' . $file->filename)) {
         return false;
     }
     if (!file_exists($destPath . '/' . $file->filename)) {
         if (!is_dir($destPath)) {
             mkdir($destPath);
         }
         $imagine = new \Imagine\Gd\Imagine();
         $imagine->open($dirPath . '/' . $file->filename)->thumbnail(new \Imagine\Image\Box(200, 200), \Imagine\Image\ImageInterface::THUMBNAIL_INSET)->save($destPath . '/' . $file->filename);
     }
     return str_replace('/assets/', '/assets/thumbs/', $file->filepath . '/' . $file->filename);
 }
Exemple #15
0
 public function afterSave($created, $options = array())
 {
     if (isset($this->data[$this->alias]['avatarf']) && !empty($this->data[$this->alias]['avatarf']['tmp_name'])) {
         $file = $this->data[$this->alias]['avatarf'];
         $dest = IMAGES . 'avatars' . DS . ceil($this->data['User']['id'] / 1000);
         if (!file_exists($dest)) {
             mkdir($dest, 0777, true);
         }
         $dest .= DS . $this->data['User']['id'] . '.jpg';
         $imagine = new Imagine\Gd\Imagine();
         try {
             $imagine->open($file['tmp_name'])->thumbnail(new Imagine\Image\Box(100, 100), Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND)->save($dest);
         } catch (Imagine\Exception\Exception $e) {
             debug($e);
         }
     }
 }
Exemple #16
0
 public function validate()
 {
     //Validate that the image uploaded is infact an image
     $types = ['image/jpeg', 'image/png', 'image/gif'];
     if (!in_array($this->file_type($this->area->file->uri), $types)) {
         return "File uploaded is not an image";
     }
     //Also validate that the image is bigger than the requested size
     $c = \Wa72\HtmlPageDom\HtmlPageCrawler::create($this->area->html);
     $size = $c->getAttribute('mvc-size') ? $c->getAttribute('mvc-size') : '1x1';
     list($width, $height) = explode('x', $size);
     $imagin = new Imagine\Gd\Imagine();
     $image = $imagin->open($this->area->file->uri);
     if ($image->getSize()->getHeight() < $height || $image->getSize()->getWidth() < $width) {
         return "Image is not big enough for saving. Please make sure the image is atleast {$size}";
     }
 }
 protected function _databaseAfterSave(Library\CommandContext $context)
 {
     $row = $context->getSubject();
     $max = $row->getContainer()->parameters->maximum_image_size;
     if ($row->isImage() && $max) {
         try {
             $imagine = new \Imagine\Gd\Imagine();
             $image = $imagine->open($row->fullpath);
             $size = $image->getSize();
             $larger = max($size->getWidth(), $size->getHeight());
             if ($larger > $max) {
                 $image->resize($size->scale($max / $larger));
                 $image->save($row->fullpath);
             }
         } catch (\Exception $e) {
         }
     }
 }
 protected function _createThumbnail($file)
 {
     @ini_set('memory_limit', '256M');
     try {
         $imagine = new \Imagine\Gd\Imagine();
         $image = $imagine->open($file);
         $size = $this->getThumbnailSize();
         $image_size = $image->getSize();
         $larger = max($image_size->getWidth(), $image_size->getHeight());
         $scale = max($size['x'], $size['y']);
         $new_size = $image_size->scale(1 / ($larger / $scale));
         $image = $image->thumbnail($new_size, \Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND);
         $file = new SplTempFileObject();
         $file->fwrite((string) $image);
         return $file;
     } catch (Exception $e) {
         return false;
     }
 }
 public function generateThumbnail()
 {
     @ini_set('memory_limit', '256M');
     $source = $this->source;
     if (!$source || $source->isNew()) {
         return false;
     }
     try {
         $imagine = new \Imagine\Gd\Imagine();
         $image = $imagine->open($source->fullpath);
         if (isset($this->x1) && isset($this->y1)) {
             $this->cropThumbnail($image);
         }
         $x = isset($this->_thumbnail_size['x']) ? $this->_thumbnail_size['x'] : 0;
         $y = isset($this->_thumbnail_size['y']) ? $this->_thumbnail_size['y'] : 0;
         // Find the biggest possible thumbnail from the given ratio (e.g 1.33)
         if (!empty($this->_thumbnail_size) && is_scalar($this->_thumbnail_size)) {
             $image_size = $image->getSize();
             $ratio = $this->_thumbnail_size;
             $width = $image_size->getWidth();
             $height = $image_size->getHeight();
             if ($width > $height) {
                 $x = min($height * $ratio, $width);
                 $y = min($height, 1 / $ratio * $x);
             } else {
                 $x = $width;
                 $y = 1 / $ratio * $width;
             }
         }
         if ($x && $y) {
             $size = new \Imagine\Image\Box($x, $y);
         } else {
             $image_size = $image->getSize();
             $larger = max($image_size->getWidth(), $image_size->getHeight());
             $scale = max($x, $y);
             $size = $image_size->scale(1 / ($larger / $scale));
         }
         return $image->thumbnail($size, \Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND);
     } catch (\Exception $e) {
         return false;
     }
 }
Exemple #20
0
 public static function thumb($file, $size = self::MEDIUM)
 {
     $dirPath = public_path() . '/' . $file;
     $destPath = public_path() . '/uploads/assets/thumbs/';
     $filename = explode('/', $file);
     $size = explode(',', $size);
     $filename = $size[0] . '_' . $size[1] . '_' . $filename[count($filename) - 1];
     if (!file_exists($dirPath)) {
         return $file;
     }
     if (!file_exists($destPath . '/' . $filename)) {
         if (!is_dir($destPath)) {
             mkdir($destPath);
         }
         $imagine = new \Imagine\Gd\Imagine();
         $imagine->open($dirPath)->thumbnail(new \Imagine\Image\Box($size[0], $size[1]), \Imagine\Image\ImageInterface::THUMBNAIL_INSET)->save($destPath . '/' . $filename);
         //     var_dump(/assets/thumbs/$filename); die;
     }
     return '/uploads/assets/thumbs/' . $filename;
 }
Exemple #21
0
 /**
  * @param string $image Name of the image
  * @param int $width Width of the image
  * @param int $height Height of the image
  *
  * @return boolean|string Thumbnail Name
  */
 public static function resize($image, $width, $height)
 {
     $path = APP_PATH . "/public/assets/uploads/images";
     if (file_exists($image)) {
         $filename = pathinfo($image, PATHINFO_FILENAME);
         $extension = pathinfo($image, PATHINFO_EXTENSION);
         if ($filename && $extension) {
             $thumbnail = "{$filename}-{$width}x{$height}.{$extension}";
             if (!file_exists("{$path}/{$thumbnail}")) {
                 $imagine = new \Imagine\Gd\Imagine();
                 $size = new \Imagine\Image\Box($width, $height);
                 $mode = \Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND;
                 $imagine->open("{$image}")->resize($size)->save("{$path}/{$thumbnail}");
                 //$imagine->open("{$path}/{$image}")->thumbnail($size, $mode)->save("{$path}/resize/{$thumbnail}");
             }
             return "{$path}/{$thumbnail}";
         }
     }
     return false;
 }
 function resizedAction()
 {
     $hash = $this->params('hash');
     $file = './data/images/' . $hash;
     $size = $this->params('size');
     preg_match('/([0-9]+)x([0-9]+)/', $size, $matches);
     $width = $matches[1];
     $height = $matches[2];
     if ($width > self::MAX || $height > self::MAX) {
         throw new Exception("that's way too big for a thumbnail, my feeble server wont handle it! Aborting.");
     }
     $newFile = './data/images/' . $size . '/' . $hash;
     $outputDir = dirname($newFile);
     if (!file_exists($outputDir)) {
         mkdir($outputDir);
     }
     $size = new \Imagine\Image\Box($width, $height);
     $mode = \Imagine\Image\ImageInterface::THUMBNAIL_INSET;
     $tmpFile = sys_get_temp_dir() . '/' . md5(uniqid()) . '.jpg';
     $imagine = new \Imagine\Gd\Imagine();
     $imagine->open($file)->thumbnail($size, $mode)->save($tmpFile, array('quality' => 100));
     rename($tmpFile, $newFile);
     return $this->getResponse()->setContent(file_get_contents($newFile));
 }
Exemple #23
0
 protected function _beforeAdd(KControllerContextInterface $context)
 {
     $state = $this->getModel()->getState();
     if ($state->container) {
         $container = $this->getModel()->getContainer();
         $size = $container->getParameters()->thumbnail_size;
         if (isset($size['x']) && isset($size['y'])) {
             $this->setThumbnailSize($size);
         }
     }
     @ini_set('memory_limit', '256M');
     if ($source = $context->request->data->file) {
         try {
             $imagine = new \Imagine\Gd\Imagine();
             $image = $imagine->open($source);
             $size = $this->getThumbnailSize();
             $image->resize(new \Imagine\Image\Box($size['x'], $size['y']));
             $string = sprintf('data:%s;base64,%s', 'image/png', base64_encode((string) $image));
             $context->request->data->thumbnail_string = $string;
         } catch (Exception $e) {
             return;
         }
     }
 }
Exemple #24
0
 public function upload()
 {
     //die("go pour upload");
     if (null == $this->filelogo) {
         return;
     }
     $extension = $this->filelogo->guessExtension();
     $nameImage = uniqid() . "." . $extension;
     $this->filelogo->move($this->getuploadRootDir(), $nameImage);
     // Création des thumbnails
     // voir doc: http://imagine.readthedocs.org/en/latest/
     $this->nom = $nameImage;
     // Création des thumbnails
     $imagine = new \Imagine\Gd\Imagine();
     $imagine->open($this->getAbsolutePath())->thumbnail(new \Imagine\Image\Box(300, 200))->save($this->getUploadRootDir() . '/thumb-small-' . $this->name);
 }
Exemple #25
0
 /**
  * Creates new group pictures in various sizes of a user, or deletes user pfotos.
  * Note: This method relies on configuration setting from main/inc/conf/profile.conf.php
  * @param	int	The group id
  * @param	string $file			The common file name for the newly created photos.
  * It will be checked and modified for compatibility with the file system.
  * If full name is provided, path component is ignored.
  * If an empty name is provided, then old user photos are deleted only,
  * @see UserManager::delete_user_picture() as the prefered way for deletion.
  * @param	string		$source_file	The full system name of the image from which user photos will be created.
  * @return	string/bool	Returns the resulting common file name of created images which usually should be stored in database.
  * When an image is removed the function returns an empty string. In case of internal error or negative validation it returns FALSE.
  */
 public function update_group_picture($group_id, $file = null, $source_file = null)
 {
     // Validation 1.
     if (empty($group_id)) {
         return false;
     }
     $delete = empty($file);
     if (empty($source_file)) {
         $source_file = $file;
     }
     // User-reserved directory where photos have to be placed.
     $path_info = self::get_group_picture_path_by_id($group_id, 'system', true);
     $path = $path_info['dir'];
     // If this directory does not exist - we create it.
     if (!file_exists($path)) {
         @mkdir($path, api_get_permissions_for_new_directories(), true);
     }
     // The old photos (if any).
     $old_file = $path_info['file'];
     // Let us delete them.
     if (!empty($old_file)) {
         if (KEEP_THE_OLD_IMAGE_AFTER_CHANGE) {
             $prefix = 'saved_' . date('Y_m_d_H_i_s') . '_' . uniqid('') . '_';
             @rename($path . 'small_' . $old_file, $path . $prefix . 'small_' . $old_file);
             @rename($path . 'medium_' . $old_file, $path . $prefix . 'medium_' . $old_file);
             @rename($path . 'big_' . $old_file, $path . $prefix . 'big_' . $old_file);
             @rename($path . $old_file, $path . $prefix . $old_file);
         } else {
             @unlink($path . 'small_' . $old_file);
             @unlink($path . 'medium_' . $old_file);
             @unlink($path . 'big_' . $old_file);
             @unlink($path . $old_file);
         }
     }
     // Exit if only deletion has been requested. Return an empty picture name.
     if ($delete) {
         return '';
     }
     // Validation 2.
     $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
     $file = str_replace('\\', '/', $file);
     $filename = ($pos = strrpos($file, '/')) !== false ? substr($file, $pos + 1) : $file;
     $extension = strtolower(substr(strrchr($filename, '.'), 1));
     if (!in_array($extension, $allowed_types)) {
         return false;
     }
     // This is the common name for the new photos.
     if (KEEP_THE_NAME_WHEN_CHANGE_IMAGE && !empty($old_file)) {
         $old_extension = strtolower(substr(strrchr($old_file, '.'), 1));
         $filename = in_array($old_extension, $allowed_types) ? substr($old_file, 0, -strlen($old_extension)) : $old_file;
         $filename = substr($filename, -1) == '.' ? $filename . $extension : $filename . '.' . $extension;
     } else {
         $filename = api_replace_dangerous_char($filename);
         if (PREFIX_IMAGE_FILENAME_WITH_UID) {
             $filename = uniqid('') . '_' . $filename;
         }
         // We always prefix user photos with user ids, so on setting
         // api_get_setting('split_users_upload_directory') === 'true'
         // the correspondent directories to be found successfully.
         $filename = $group_id . '_' . $filename;
     }
     // Storing the new photos in 4 versions with various sizes.
     /*$image->resize(
       // get original size and set width (widen) or height (heighten).
       // width or height will be set maintaining aspect ratio.
           $image->getSize()->widen( 700 )
       );*/
     // Usign the Imagine service
     $imagine = new Imagine\Gd\Imagine();
     $image = $imagine->open($source_file);
     $options = array('quality' => 90);
     //$image->resize(new Imagine\Image\Box(200, 200))->save($path.'big_'.$filename);
     $image->resize($image->getSize()->widen(200))->save($path . 'big_' . $filename, $options);
     $image = $imagine->open($source_file);
     $image->resize(new Imagine\Image\Box(85, 85))->save($path . 'medium_' . $filename, $options);
     $image = $imagine->open($source_file);
     $image->resize(new Imagine\Image\Box(22, 22))->save($path . 'small_' . $filename);
     /*
             $small  = self::resize_picture($source_file, 22);
             $medium = self::resize_picture($source_file, 85);
             $normal = self::resize_picture($source_file, 200);
     
             $big = new Image($source_file); // This is the original picture.
             $ok = $small && $small->send_image($path.'small_'.$filename)
                 && $medium && $medium->send_image($path.'medium_'.$filename)
                 && $normal && $normal->send_image($path.'big_'.$filename)
                 && $big && $big->send_image($path.$filename);
             return $ok ? $filename : false;*/
     return $filename;
 }
Exemple #26
0
 /**
  * @ORM\PostPersist()
  * @ORM\PostUpdate()
  */
 public function upload()
 {
     //die("go pour upload");
     if (null == $this->fichier) {
         return;
     }
     // Suppression des anciennes images
     //condition pour supprimer une et la remplacée par une autre
     if ($this->oldFichier) {
         // Suppression des images
         // Suppression de l'image principale
         unlink($this->getUploadRootDir() . '/' . $this->oldFichier);
         //Suppression des thumbnails
         foreach ($this->thumbnails as $key => $value) {
             unlink($this->getUploadRootDir() . '/' . $key . '-' . $this->oldFichier);
         }
     }
     /*
     $extension = $this->fichier->guessExtension();
     
     $nameImage = uniqid().".".$extension;
     $this->fichier->move($this->getuploadRootDir(),
         $nameImage);
     
     // Création des thumbnails
     // voir doc: http://imagine.readthedocs.org/en/latest/
     
     $this->name=$nameImage;
     */
     $this->fichier->move($this->getuploadRootDir(), $this->name);
     // Création des thumbnails
     $imagine = new \Imagine\Gd\Imagine();
     $imagineOpen = $imagine->open($this->getAbsolutePath());
     foreach ($this->thumbnails as $key => $value) {
         $imagineOpen->thumbnail(new \Imagine\Image\Box($value[0], $value[1]))->save($this->getUploadRootDir() . '/' . $key . '-' . $this->name);
     }
 }
Exemple #27
0
    if (isset($_FILES['preview'])) {
        // загружаем превью
        if ($_FILES['preview']['size']) {
            unset($data['preview']);
            $preview_file = $_FILES['preview'];
            list($name, $ext) = explode('.', $preview_file['name']);
            $filename = 'orig_' . $id . '.' . $ext;
            $thumb_name = 'thumb_' . $id . '.' . $ext;
            $upload_dir = $app->config('upload.path');
            $file_path = $upload_dir . '/' . $filename;
            $thumb_path = $upload_dir . '/' . $thumb_name;
            if (move_uploaded_file($preview_file['tmp_name'], $file_path) === true) {
                $imagine = new Imagine\Gd\Imagine();
                $size = new Imagine\Image\Box(500, 500);
                $mode = Imagine\Image\ImageInterface::THUMBNAIL_INSET;
                $imagine->open($file_path)->thumbnail($size, $mode)->save($thumb_path);
                $data['preview_url'] = $thumb_path;
            }
        }
    }
    try {
        Lot::patch($id, $data);
        $app->flash('success', 'Данные лота обновлены!');
    } catch (Exception $e) {
        // что-то пошло не так
        $app->flash('error', $e->getMessage());
    }
    $app->redirect($app->urlFor('lots'));
});
// удаление лота
$app->get('/delete_lot/:id', function ($id) use($app) {
Exemple #28
0
 /**
  * 开始处理裁剪
  *
  * @param  string $realFile 所要处理的图片的位置
  * @param  string $savePath 所要保存的位置
  * @return string           处理后的图片
  */
 private function cutImage($realFile, $savePath)
 {
     if (!isImage($this->file->getClientOriginalExtension())) {
         throw new \Exception("Image thumb must be images.");
     }
     $imagine = new \Imagine\Gd\Imagine();
     $mode = \Imagine\Image\ImageInterface::THUMBNAIL_INSET;
     $result = [];
     foreach ($this->params['thumbSetting'] as $key => $value) {
         if (isset($value['width'], $value['height']) and is_numeric($value['width']) and is_numeric($value['height'])) {
             $size = new \Imagine\Image\Box($value['width'], $value['height']);
             $saveName = $savePath . $this->getSaveFileName() . '_' . $value['width'] . '_' . $value['height'] . '_thumb.' . $this->file->getClientOriginalExtension();
             $imagine->open($realFile)->thumbnail($size, $mode)->save($saveName);
             $result[] = str_replace('/', '', str_replace($this->getConfigSavePath(), '', $saveName));
         }
     }
     return $result;
 }
Exemple #29
0
 public function getReceipt($id, $hash)
 {
     $this->blockUnloggedOne($id, true);
     $imagine = new Imagine\Gd\Imagine();
     $image = $imagine->open('./data/receipt/' . $id . '.png');
     $this->session->set_userdata('random_hash_2', $hash);
     $image->show('png');
 }
 public function process($file_temp_name, $config = null)
 {
     $errors = [];
     if (is_null($config)) {
         $config = VariationHelper::getConfigOfType($this->type);
     }
     $is_image = $this->isImage();
     if (!$is_image || isset($config['_original']) && $config['_original'] === true) {
         $upload_dir = $this->getUploadDir($this->type);
         if (!is_dir($upload_dir)) {
             mkdir($upload_dir, 0777, true);
         }
         $upload_full_path = $upload_dir . DIRECTORY_SEPARATOR . $this->filename;
         if (!move_uploaded_file($file_temp_name, $upload_full_path)) {
             array_push($errors, 'Can not move uploaded file.');
         }
     } else {
         $upload_full_path = $file_temp_name;
     }
     if (!$is_image) {
         return $errors;
     }
     try {
         switch ($this->image_driver) {
             case self::IMAGE_DRIVER_IMAGICK:
                 $imagine = new \Imagine\Imagick\Imagine();
                 break;
             case self::IMAGE_DRIVER_GMAGICK:
                 $imagine = new \Imagine\Gmagick\Imagine();
                 break;
             default:
                 //case self::IMAGE_DRIVER_GD:
                 $imagine = new \Imagine\Gd\Imagine();
                 break;
         }
         $image = $imagine->open($upload_full_path);
         foreach ($config as $variation_name => $variation_config) {
             if (substr($variation_name, 0, 1) !== '_' || $variation_name == '_thumb') {
                 $errors = array_merge($errors, $this->makeVariation($imagine, $image, $variation_name, $variation_config));
             }
         }
     } catch (\Imagine\Exception\Exception $e) {
         // handle the exception
         array_push($errors, $e->getMessage());
     }
     return $errors;
 }