Exemple #1
0
 protected function handle()
 {
     $request = $this->getRequest();
     $posts = $request->request;
     $file_path = $posts->get('image_path');
     $x = $posts->get('x');
     $y = $posts->get('y');
     $w = $posts->get('w');
     $h = $posts->get('h');
     $path_info = pathinfo($file_path);
     $imagine = new Imagine();
     $raw_image = $imagine->open($file_path);
     $large_image = $raw_image->copy();
     $large_image->crop(new Point($x, $y), new Box($w, $h));
     $large_file_path = "{$path_info['dirname']}/{$path_info['filename']}_large.{$path_info['extension']}";
     $large_image->save($large_file_path, array('quality' => 70));
     $origin_dir_name = $path_info['dirname'];
     $new_directory = str_replace('/tmp', '', $origin_dir_name);
     $new_file = new File($large_file_path);
     $new_file->move($new_directory, "{$path_info['filename']}.{$path_info['extension']}");
     $container = $this->getContainer();
     $cdn_url = $container->getParameter('cdn_url');
     $new_uri = $cdn_url . '/upload/' . $path_info['filename'] . '.' . $path_info['extension'];
     @unlink($large_file_path);
     @unlink($file_path);
     return new JsonResponse(array('picture_uri' => $new_uri));
 }
Exemple #2
0
 /**
  * {@inheritdoc}
  */
 public function resize($imagePath, array $size, $mode, $force = false)
 {
     $cacheKey = $this->getCacheKey($size, $mode);
     $filename = basename($imagePath);
     if (false === $force && $this->imageCache->contains($filename, $cacheKey)) {
         return $this->imageCache->getRelativePath($filename, $cacheKey);
     }
     $cacheAbsolutePath = $this->imageCache->getAbsolutePath($filename, $cacheKey);
     $imagine = new Imagine();
     $imagineImage = $imagine->open($this->filesystem->getRootDir() . $imagePath);
     $imageSize = array($imagineImage->getSize()->getWidth(), $imagineImage->getSize()->getHeight());
     $boxSize = $this->resizeHelper->getBoxSize($imageSize, $size);
     $box = $this->getBox($boxSize[0], $boxSize[1]);
     if (ImageResizerInterface::INSET === $mode) {
         $imageSizeInBox = $this->resizeHelper->getImageSizeInBox($imageSize, $boxSize);
         $imagineImage->resize($this->getBox($imageSizeInBox[0], $imageSizeInBox[1]));
         $palette = new RGB();
         $box = $imagine->create($box, $palette->color($this->color, $this->alpha));
         $imagineImage = $box->paste($imagineImage, $this->getPointInBox($imageSizeInBox, $boxSize));
     } else {
         $imagineImage = $imagineImage->thumbnail($box);
     }
     $this->filesystem->mkdir(dirname($cacheAbsolutePath));
     $imagineImage->save($cacheAbsolutePath, ImageOptionHelper::getOption($filename));
     return $this->imageCache->getRelativePath($filename, $cacheKey);
 }
Exemple #3
0
 /**
  * @param Picture $picture
  * @param array $data
  */
 protected function postSave(Picture $picture, array $data)
 {
     if (isset($data['meta']) && isset($data['meta']['filename'])) {
         $module = $this->getServiceContainer()->getModuleManager()->load('gossi/trixionary');
         $file = new File($module->getUploadPath()->append($data['meta']['filename']));
         $slugifier = new Slugify();
         $filename = sprintf('%s-%u.%s', $slugifier->slugify($picture->getAthlete()), $picture->getId(), $file->getExtension());
         $filepath = $module->getPicturesPath($picture->getSkill())->append($filename);
         $file->move($filepath);
         // create thumb folder
         $thumbspath = $module->getPicturesPath($picture->getSkill())->append('thumbs');
         $dir = new Directory($thumbspath);
         if (!$dir->exists()) {
             $dir->make();
         }
         // create thumb
         $imagine = new Imagine();
         $image = $imagine->open($filepath->toString());
         $max = max($image->getSize()->getWidth(), $image->getSize()->getHeight());
         $width = $image->getSize()->getWidth() / $max * self::THUMB_MAX_SIZE;
         $height = $image->getSize()->getHeight() / $max * self::THUMB_MAX_SIZE;
         $size = new Box($width, $height);
         $thumbpath = $thumbspath->append($filename);
         $image->thumbnail($size)->save($thumbpath->toString());
         // save to picture
         $picture->setUrl($module->getPicturesUrl($picture->getSkill()) . '/' . $filename);
         $picture->setThumbUrl($module->getPicturesUrl($picture->getSkill()) . '/thumbs/' . $filename);
         $picture->save();
     }
     // activity
     $user = $this->getServiceContainer()->getAuthManager()->getUser();
     $user->newActivity(array('verb' => $this->isNew ? Activity::VERB_UPLOAD : Activity::VERB_EDIT, 'object' => $picture, 'target' => $picture->getSkill()));
 }
Exemple #4
0
 public function save()
 {
     $model = Books::findOne($this->id);
     $fileInstance = UploadedFile::getInstance($this, self::FIELD_PREVIEW);
     if ($fileInstance) {
         $filePath = 'images/' . $fileInstance->baseName . '.' . $fileInstance->extension;
         $model->preview = $fileInstance->baseName . '.' . $fileInstance->extension;
         $fileInstance->saveAs($filePath, false);
         $imagine = new Gd\Imagine();
         try {
             $filePath = 'images/preview_' . $fileInstance->baseName . '.' . $fileInstance->extension;
             $img = $imagine->open($fileInstance->tempName);
             $size = $img->getSize();
             if ($size->getHeight() > $this->imageSizeLimit['width'] || $size->getWidth() > $this->imageSizeLimit['height']) {
                 $img->resize(new Box($this->imageSizeLimit['width'], $this->imageSizeLimit['height']));
             }
             $img->save($filePath);
             //
         } catch (\Imagine\Exception\RuntimeException $ex) {
             $this->addError(self::FIELD_PREVIEW, 'Imagine runtime exception: ' . $ex->getMessage());
             return FALSE;
         }
     }
     if (!$this->validate()) {
         return false;
     }
     $model->name = $this->name;
     $model->author_id = $this->author_id;
     $model->date = DateTime::createFromFormat('d/m/Y', $this->date)->format('Y-m-d');
     $model->date_update = new Expression('NOW()');
     $model->save();
     return true;
 }
 /**
  * @param \CActiveRecord $model
  * @param string $attribute имя поля, содержащего CUploadedFile. В последствии этому полю будет присвоено имя файла изображения.
  * @param \CUploadedFile $image
  * @param array $sizes
  *
  * @throws \CException
  *
  * @return bool
  */
 public function save(\CActiveRecord $model, $attribute = 'image', \CUploadedFile $image, $sizes = [])
 {
     $folderModel = $this->extractPath($model, $attribute, true);
     if (!file_exists($folderModel)) {
         mkdir($folderModel);
     }
     $imageExtension = isset($this->mimeToExtension[$image->getType()]) ? $this->mimeToExtension[$image->getType()] : 'jpg';
     $imageId = $this->getRandomHash($model, $attribute);
     $imagePathTemp = \Yii::getPathOfAlias('temp') . '/' . $imageId . '.' . $imageExtension;
     if ($image->saveAs($imagePathTemp)) {
         foreach ($sizes as $sizeName => $size) {
             $folderModelAttribute = $this->extractPath($model, $attribute);
             if (!file_exists($folderModelAttribute)) {
                 mkdir($folderModelAttribute);
             }
             $quality = array_key_exists('quality', $size) ? intval($size['quality']) : self::DEFAULT_QUALITY;
             if ($quality <= 0 or $quality > 100) {
                 $quality = self::DEFAULT_QUALITY;
             }
             $pathImageSize = $folderModelAttribute . '/' . $imageId . '_' . $sizeName . '.' . $imageExtension;
             if (array_key_exists('enabled', $size) and $size['enabled'] == false) {
                 if (array_key_exists('resave', $size) and $size['resave'] == false) {
                     rename($imagePathTemp, $pathImageSize);
                 } else {
                     $this->processor->open($imagePathTemp)->save($pathImageSize, ['quality' => $quality]);
                 }
             } else {
                 $this->processor->open($imagePathTemp)->thumbnail(new Box($size['width'], $size['height']), (!isset($size['inset']) or $size['inset']) ? ImageInterface::THUMBNAIL_INSET : ImageInterface::THUMBNAIL_OUTBOUND)->save($pathImageSize, ['quality' => $quality]);
             }
         }
     } else {
         throw new \CException('can not save image');
     }
     return [self::KEY_ID => $imageId, self::KEY_EXT => $imageExtension];
 }
Exemple #6
0
 /**
  * @param Sport $sport
  * @param array $data
  */
 protected function postSave(Sport $sport, array $data)
 {
     // upload picture
     if (isset($data['meta']) && isset($data['meta']['filename']) && !empty($data['meta']['filename'])) {
         $module = $this->getServiceContainer()->getModuleManager()->load('gossi/trixionary');
         // ensure directory
         $dir = new Directory($module->getSportPath($sport));
         if (!$dir->exists()) {
             $dir->make();
         }
         $destpath = $module->getSkillPreviewPath($sport);
         $dest = new File($destpath);
         if ($dest->exists()) {
             $dest->delete();
         }
         $file = new File($module->getUploadPath()->append($data['meta']['filename']));
         $imagine = new Imagine();
         $image = $imagine->open($file->toPath()->toString());
         $image->save($dest->toPath()->toString());
         $file->delete();
         $sport->setSkillPictureUrl($module->getSkillPreviewUrl($sport));
         $sport->save();
     }
     // delete picture
     if (isset($data['meta']) && isset($data['meta']['skill_picture_delete']) && $data['meta']['skill_picture_delete'] == 1) {
         $module = $this->getServiceContainer()->getModuleManager()->load('gossi/trixionary');
         $path = $module->getSkillPreviewPath($sport);
         $file = new File($path);
         $file->delete();
         $sport->setSkillPictureUrl(null);
         $sport->save();
     }
 }
 public function testGetExceptionWithInvalidWatermarkSize()
 {
     $this->setExpectedException('HtImgModule\\Exception\\InvalidArgumentException');
     $imagine = new Imagine();
     $archos = $imagine->open('resources/Archos.jpg');
     $watermark = new Watermark($archos, 'asfd', 'asdf');
 }
Exemple #8
0
 /**
  * Turn an image Negative
  *
  * @param string $file
  * @param array $arguments
  * @param array $typeOptions
  *
  * @return void
  */
 public function doFilter($file, $arguments, $typeOptions)
 {
     $Imagine = new Imagine();
     $image = $Imagine->open($file);
     $image->effects()->negative();
     $image->save($file);
 }
Exemple #9
0
 /**
  * @param     $img
  * @param int $width
  * @param int $height
  * @return \Imagine\Image\ManipulatorInterface
  */
 public function toThumbnail($img, $width = 120, $height = 120)
 {
     $thumbnail = pathinfo($img, PATHINFO_DIRNAME) . '/' . pathinfo($img, PATHINFO_FILENAME) . '_thumbnil.' . pathinfo($img, PATHINFO_EXTENSION);
     $imagine = new Imagine();
     $imagine->open($img)->thumbnail(new Box($width, $height), ImageInterface::THUMBNAIL_OUTBOUND)->save($thumbnail);
     return $thumbnail;
 }
Exemple #10
0
 public function actionIndex($type = null, $size = null, $pictureFilename = null, $extension = null)
 {
     try {
         ini_set('memory_limit', '1024M');
         error_reporting(1);
         list($x, $y) = explode('x', $size);
         $imagine = new Imagine();
         $picture = $imagine->open(\Yii::$app->basePath . '/web/pictures/' . $type . '/full_size/' . $pictureFilename . '.' . $extension);
         $pictureSize = $picture->getSize();
         $pictureWidth = $pictureSize->getWidth();
         $pictureHeight = $pictureSize->getHeight();
         if (!$x) {
             $aspectRatio = $pictureWidth / $pictureHeight;
         } elseif (!$y) {
             $aspectRatio = $pictureHeight / $pictureWidth;
         }
         $y = $y ? $y : round($aspectRatio * $x);
         $x = $x ? $x : round($aspectRatio * $y);
         $box = new Box($x, $y, ImageInterface::FILTER_UNDEFINED);
         $mode = ImageInterface::THUMBNAIL_OUTBOUND;
         $thumbnail = $picture->thumbnail($box, $mode);
         $thumbnailSize = $thumbnail->getSize();
         $thumbnailX = $thumbnailSize->getWidth();
         $xPos = $x / 2 - $thumbnailX / 2;
         $color = $extension == 'png' ? new Color('#fff', 100) : new Color('#fff');
         $imagine->create($box, $color)->paste($thumbnail, new Point($xPos, 0))->save(\Yii::$app->basePath . '/web/pictures/' . $type . '/' . $size . '/' . $pictureFilename . '.' . $extension)->show($extension);
     } catch (Exception $e) {
         return false;
     }
 }
 public function upload($width = 593, $height = 393)
 {
     // la propriété « file » peut être vide si le champ n'est pas requis
     if (null === $this->file) {
         return;
     }
     // utilisez le nom de fichier original ici mais
     // vous devriez « l'assainir » pour au moins éviter
     // quelconques problèmes de sécurité
     // la méthode « move » prend comme arguments le répertoire cible et
     // le nom de fichier cible où le fichier doit être déplacé
     $clean_file = $this->slugify($this->file->getClientOriginalName());
     $clean_file = str_replace($this->file->guessClientExtension(), "", $clean_file) . "." . $this->file->guessClientExtension();
     $this->file->move($this->getUploadRootDir() . "tmp/", $clean_file);
     $imagine = new Imagine();
     $size = new Box($width, $height);
     $image = $imagine->open($this->getUploadRootDir() . "tmp/" . $clean_file);
     //original size
     $srcBox = $image->getSize();
     $thumbnail_lg = $image->thumbnail($size, \Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND);
     $thumbnail_lg->save($this->getUploadRootDir() . "/" . $clean_file);
     $thumbnail_sm = $image->thumbnail($size, \Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND);
     $thumbnail_sm->save($this->getUploadRootDir() . "/thumbnail/" . $clean_file);
     // définit la propriété « path » comme étant le nom de fichier où vous
     // avez stocké le fichier
     $this->path = $clean_file;
     // « nettoie » la propriété « file » comme vous n'en aurez plus besoin
     $this->file = null;
 }
 public function createImages($aTypeImage, $sImageName)
 {
     foreach ($aTypeImage as $oTypeImage) {
         $oImagine = new Imagine();
         $oImagine->open(self::BUNDLE_IMAGE_DIR . "source/" . $sImageName)->resize(new Box($oTypeImage->getWidth(), $oTypeImage->getHeight()))->save(self::BUNDLE_IMAGE_DIR . $oTypeImage->getDir() . '/' . $sImageName, array('jpeg_quality' => 100));
     }
 }
 public function __construct(GoPro $gopro, GithubDarkroom $githubDarkroom, Imagine $imagine, $watermark)
 {
     $this->gopro = $gopro;
     $this->darkroom = $githubDarkroom;
     $this->imagine = $imagine;
     $this->watermark = $imagine->open($watermark);
 }
 /**
  * @param $image
  */
 public function __construct($image)
 {
     $this->validate($image);
     self::$ext = $image->getClientOriginalExtension();
     $img = new Img();
     $this->image = $img->open($image);
 }
 /**
  * @inheritdoc
  */
 public function resize($binaryData, array $settings)
 {
     $imagine = new Imagine();
     $image = $imagine->load($binaryData);
     $image->resize(new Box($settings['width'], $settings['height']));
     return $image->get('png');
 }
Exemple #16
0
function fix_orientation($source, $name)
{
    $imginfo = getimagesize($source);
    $requiredMemory1 = ceil($imginfo[0] * $imginfo[1] * 5.35);
    $requiredMemory2 = ceil($imginfo[0] * $imginfo[1] * ($imginfo['bits'] / 8) * $imginfo['channels'] * 2.5);
    $requiredMemory = (int) max($requiredMemory1, $requiredMemory2);
    $mem_avail = elgg_get_ini_setting_in_bytes('memory_limit');
    $mem_used = memory_get_usage();
    $mem_avail = $mem_avail - $mem_used - 2097152;
    // 2 MB buffer
    if ($requiredMemory > $mem_avail) {
        // we don't have enough memory for any manipulation
        // @TODO - we should only throw an error if the image needs rotating...
        //register_error(elgg_echo('image_orientation:toolarge'));
        return false;
    }
    elgg_load_library('imagine');
    $name = uniqid() . $name;
    $tmp_location = elgg_get_config('dataroot') . 'image_orientation/' . $name;
    //@note - need to copy to a tmp_location as
    // imagine doesn't like images with no file extension
    copy($source, $tmp_location);
    try {
        $imagine = new Imagine();
        $imagine->setMetadataReader(new ExifMetadataReader());
        $autorotate = new Autorotate();
        $autorotate->apply($imagine->open($tmp_location))->save($tmp_location);
        copy($tmp_location, $source);
        unlink($tmp_location);
        return true;
    } catch (Imagine\Exception\Exception $exc) {
        // fail silently, we don't need to rotate it bad enough to kill the script
        return false;
    }
}
Exemple #17
0
 protected function getPictureAttributes($filename, $type)
 {
     $filename = str_replace('!', '.', $filename);
     $filename = str_replace(array('..', '/', '\\'), '', $filename);
     $picture_file_path = APP_ROOT . '/app/cdn/tmp/' . $filename;
     try {
         $imagine = new Imagine();
         $image = $imagine->open($picture_file_path);
         $natural_size = $image->getSize();
         if ($type == 'icon') {
             $scale_ratio = 596 / $natural_size->getWidth();
         } else {
             $scale_ratio = 868 / $natural_size->getWidth();
         }
         $box = new Box($natural_size->getWidth(), $natural_size->getHeight());
         $box = $box->scale($scale_ratio);
         $image->resize($box);
         $image->save($picture_file_path);
     } catch (\Exception $e) {
         @unlink($picture_file_path);
         throw new \Exception($e->getMessage());
     }
     $cdn_url = $this->getContainer()->getParameter('cdn_url');
     $picture_url = $cdn_url . '/tmp/' . $filename;
     return array('natural_size' => $box, 'picture_url' => $picture_url, 'picture_path' => $picture_file_path);
 }
 /**
  * Crops avatar image to square and corrects orientation.
  *
  * @return void
  */
 private function cropAvatar()
 {
     // Image manipulation class part of codesleeve/laravel-stapler.
     $imagine = new Imagine();
     // Gets full path of uploaded avatar, creates Imagine object to manipulate image.
     $avatarPath = \Auth::user()->avatar->url();
     $image = $imagine->open(public_path() . $avatarPath);
     // Reads EXIF data with a wrapper around native exif_read_data() PHP function.
     $reader = Reader::factory(Reader::TYPE_NATIVE);
     $exifData = $reader->getExifFromFile(public_path() . $avatarPath)->getRawData();
     $width = NULL;
     $height = NULL;
     if (array_key_exists('ExifImageWidth', $exifData) && array_key_exists('ExifImageLength')) {
         $width = $exifData['ExifImageWidth'];
         $height = $exifData['ExifImageLength'];
     } else {
         if (array_key_exists('COMPUTED', $exifData)) {
             $width = $exifData['COMPUTED']['Width'];
             $height = $exifData['COMPUTED']['Height'];
         } else {
             return false;
         }
     }
     // Crops off top and  bottom for tall images.
     if ($height > $width) {
         $start = ($height - $width) / 2;
         $image->crop(new Point(0, $start), new Box($width, $width));
     } else {
         $start = ($width - $height) / 2;
         $image->crop(new Point($start, 0), new Box($height, $height));
     }
     // In case image does not have all EXIF data, including orientation.
     // Setting EXIF orientation to 1 stores the image as it is originally
     // oriented.
     if (!array_key_exists('Orientation', $exifData)) {
         $exifData['Orientation'] = 1;
     }
     // Adjusts orientation depending on EXIF orientation data.
     switch ($exifData['Orientation']) {
         // Rotates image if it is upside down.
         case 3:
             $image->rotate(180);
             break;
             // Rotates image 90 degrees to the right.
         // Rotates image 90 degrees to the right.
         case 6:
             $image->rotate(90);
             break;
             // Rotates image 90 degrees to the left.
         // Rotates image 90 degrees to the left.
         case 8:
             $image->rotate(-90);
             break;
     }
     // Replaces original avatar and ensures previous image is deleted.
     File::delete(public_path() . $avatarPath);
     $image->save(public_path() . $avatarPath);
     return true;
 }
Exemple #19
0
 /**
  * Colorize an image
  *
  * @param string $file
  * @param array $arguments
  * @param array $typeOptions
  *
  * @return void
  */
 public function doFilter($file, $arguments, $typeOptions)
 {
     $Imagine = new Imagine();
     $image = $Imagine->open($file);
     $colour = new Color('#' . $arguments['colorize']);
     $image->effects()->colorize($colour);
     $image->save($file);
 }
 /**
  * @test
  * @dataProvider photos
  * @param $photo
  */
 public function generate($photo)
 {
     $photoThumb = $this->thumbGenerator->generate(new ThumbId(), $photo, new PhotoThumbSize(95, 95), new HttpUrl('http://test'));
     $image = $this->imagine->open($photoThumb->photoThumbFile()->filePath());
     $this->assertEquals(95, $image->getSize()->getHeight());
     $this->assertEquals(95, $image->getSize()->getWidth());
     unlink($photoThumb->photoThumbFile()->filePath());
 }
 public function testFilter()
 {
     $imagine = new Imagine();
     $filter1 = new Background($imagine, [1050, 1060], '#ddd');
     $filter2 = new Background($imagine, [1550, 1560], '#bbb');
     $chain = new Chain([$filter1, $filter2]);
     $archos = $imagine->open('resources/Archos.jpg');
     $chain->apply($archos);
 }
Exemple #22
0
 /**
  * Lists all Image models.
  * @param int $id product id
  * @return mixed
  *
  * @throws NotFoundHttpException
  */
 public function actionIndex($id)
 {
     $form = new MultipleUploadForm();
     if (!Product::find()->where(['id' => $id])->exists()) {
         throw new NotFoundHttpException();
     }
     $searchModel = new ImageSearch();
     $searchModel->product_id = $id;
     $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
     if (Yii::$app->request->isPost) {
         $form->files = UploadedFile::getInstances($form, 'files');
         if ($form->files && $form->validate()) {
             foreach ($form->files as $file) {
                 //
                 // UPLOADING THE IMAGE:
                 //
                 $image = new Image();
                 $image->product_id = $id;
                 if ($image->save()) {
                     // Save an original image;
                     $path = $image->getPath();
                     $file->saveAs($path);
                     // Original size:
                     $size = getimagesize($path);
                     $height = $size[1];
                     $width = $size[0];
                     // IMAGINE
                     ImagineImage::$driver = [ImagineImage::DRIVER_GD2];
                     $imagine = new Imagine();
                     $picture = $imagine->open($path);
                     //---------------------------
                     //                        $size = new Box(self::IMAGE_WIDTH, self::IMAGE_HEIGHT);
                     //                        $center = new Center($size);
                     //---------------------------
                     //                        $picture->crop(new Point(0, 0),
                     //                            new Box(self::IMAGE_WIDTH, self::IMAGE_HEIGHT))->save($path);
                     /**
                      * If the image's height is bigger than needed, it must be cut.
                      * Otherwise it must be resized.
                      */
                     if ($height >= self::IMAGE_HEIGHT) {
                         $picture->thumbnail(new Box(self::IMAGE_WIDTH, self::IMAGE_HEIGHT))->save($path, ['quality' => 100]);
                         // re-save cropped image;
                     } else {
                         $picture->resize(new Box(self::IMAGE_WIDTH, self::IMAGE_HEIGHT))->save($path);
                     }
                     sleep(1);
                     //                        $background = new Color('#FFF');
                     //                        $topLeft    = new Point(0, 0);
                     //                        $canvas = $imagine->create(new Box(450, 450), $background);
                     //                        $canvas->paste($picture, $topLeft)->save($path);
                 }
             }
         }
     }
     return $this->render('index', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'uploadForm' => $form]);
 }
Exemple #23
0
 protected function setUp()
 {
     $this->imagePath = Core\Config()->paths('root') . 'image.png';
     $this->width = 640;
     $this->height = 480;
     $this->size = array("{$this->width}x{$this->height}", "{$this->height}x{$this->width}");
     $imagine = new Imagine();
     $this->image = $imagine->create(new Box($this->width * 2, $this->width * 2))->save($this->imagePath);
 }
Exemple #24
0
 public function testShouldResize()
 {
     $size = new Box(100, 10);
     $imagine = new Imagine();
     $imagine->open('tests/Imagine/Fixtures/large.jpg')->thumbnail($size, ImageInterface::THUMBNAIL_OUTBOUND)->save('tests/Imagine/Fixtures/resized.jpg');
     $this->assertTrue(file_exists('tests/Imagine/Fixtures/resized.jpg'));
     $this->assertEquals($size, $imagine->open('tests/Imagine/Fixtures/resized.jpg')->getSize());
     unlink('tests/Imagine/Fixtures/resized.jpg');
 }
 public function changePicture($filePath)
 {
     $pathinfo = pathinfo($filePath);
     $imagine = new Imagine();
     $rawImage = $imagine->open($filePath);
     $FileRecord = $this->getFileService()->uploadFile('brand', new File($filePath));
     @unlink($filePath);
     return $FileRecord['uri'];
 }
 /**
  * Resize a resource image
  *
  * @param string $file
  * @param string $path
  * @param integer $width
  * @param integer $height
  * @param string $newPath
  * @param boolean $saveProportions
  * @return void
  */
 public static function resizeResourceImage($file, $path, $width, $height, $newPath = null, $saveProportions = true)
 {
     $filePath = ApplicationService::getResourcesDir() . $path . $file;
     // resize the avatar
     $imagine = new Imagine\Gd\Imagine();
     $size = new Imagine\Image\Box($width, $height);
     $mode = $saveProportions ? Imagine\Image\ImageInterface::THUMBNAIL_INSET : Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND;
     $imagine->open($filePath)->thumbnail($size, $mode)->save($newPath ? ApplicationService::getResourcesDir() . $newPath . $file : $filePath);
 }
 /**
  * Import a user in the database
  *
  * @param Organization $bdeOrga
  * @param bool $flush
  * @return \Etu\Core\UserBundle\Entity\User
  */
 protected function importUser($bdeOrga = null, $flush = false)
 {
     $imagine = new Imagine();
     $webDirectory = __DIR__ . '/../../../../../../../web';
     $avatar = $this->element->getLogin() . '.jpg';
     if (!file_exists($webDirectory . '/uploads/photos/' . $this->element->getLogin() . '.jpg')) {
         // Resize photo
         try {
             $image = $imagine->open('http://local-sig.utt.fr/Pub/trombi/individu/' . $this->element->getStudentId() . '.jpg');
             $image->copy()->thumbnail(new Box(200, 200), Image::THUMBNAIL_OUTBOUND)->save($webDirectory . '/uploads/photos/' . $this->element->getLogin() . '.jpg');
         } catch (\Exception $e) {
             $avatar = 'default-avatar.png';
         }
     }
     $niveau = null;
     $branch = $this->element->getNiveau();
     preg_match('/^[^0-9]+/i', $this->element->getNiveau(), $match);
     if (isset($match[0])) {
         $branch = $match[0];
         $niveau = str_replace($branch, '', $this->element->getNiveau());
     }
     $user = new \Etu\Core\UserBundle\Entity\User();
     $user->setAvatar($avatar);
     $user->setLogin($this->element->getLogin());
     $user->setFullName($this->element->getFullName());
     $user->setFirstName($this->element->getFirstName());
     $user->setLastName($this->element->getLastName());
     $user->setFiliere($this->element->getFiliere());
     $user->setFormation(ucfirst(strtolower($this->element->getFormation())));
     $user->setNiveau($niveau);
     $user->setBranch($branch);
     $user->setMail($this->element->getMail());
     $user->setPhoneNumber($this->element->getPhoneNumber());
     $user->setRoom($this->element->getRoom());
     $user->setStudentId($this->element->getStudentId());
     $user->setTitle($this->element->getTitle());
     $user->setIsStudent($this->element->getIsStudent());
     $user->setKeepActive(false);
     $user->setUvs(implode('|', $this->element->getUvs()));
     $this->doctrine->getManager()->persist($user);
     // Subscribe to BDE
     if ($bdeOrga) {
         $subscription = new Subscription();
         $subscription->setEntityType('orga')->setEntityId($bdeOrga->getId())->setUser($user);
         $this->doctrine->getManager()->persist($subscription);
     }
     // Subscribe to all events
     $subscription = new Subscription();
     $subscription->setEntityType('event')->setEntityId(0)->setUser($user);
     $this->doctrine->getManager()->persist($subscription);
     // Flush if needed
     if ($flush) {
         $this->doctrine->getManager()->flush();
     }
     return $user;
 }
 public function testConvertStringCoordinateToNumber()
 {
     $imagine = new Imagine();
     $flowers = $imagine->open('resources/flowers.jpg');
     $archos = $imagine->open('resources/Archos.jpg');
     $paste = new Paste($archos, 'center', 'top');
     $newImage = $paste->apply($flowers);
     $paste = new Paste($archos, 'left', 'bottom');
     $newImage = $paste->apply($flowers);
 }
 protected function addOverlay($pictureUrl)
 {
     $imagine = new Imagine();
     $picture = $imagine->open($pictureUrl);
     $overlay = $imagine->open($this->storagePath . env('FACEBOOK_OVERLAY'));
     $x = $picture->getSize()->getWidth() - $overlay->getSize()->getWidth();
     $y = $picture->getSize()->getHeight() - $overlay->getSize()->getHeight();
     $picture->paste($overlay, new Point($x, $y));
     return $picture;
 }
 public function testLoad()
 {
     $loader = new DownscaleFilterLoader();
     $imagine = new Imagine();
     $image = $imagine->open(__DIR__ . '/../../../Fixtures/assets/square-300x300.png');
     $options = array('max' => array(201, 201));
     $image = $loader->load($image, $options);
     $size = $image->getSize();
     $this->assertEquals($options['max'], array($size->getWidth(), $size->getHeight()));
 }