/** * @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]; }
/** * @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 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 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; }
/** * @param string $origName * @param string $thumbName * @param array $origInfo */ public function resize($origName, $thumbName, array $origInfo) { if ($this->shouldResize($origInfo)) { $resizeParameters = $this->getResizeParameters($origInfo); $cropParameters = $this->getCropParameters($resizeParameters); $resizeSize = $this->factory->getBox($resizeParameters[0], $resizeParameters[1]); $cropStart = $this->factory->getPoint($cropParameters[0], $cropParameters[1]); $cropSize = $this->factory->getBox($this->thumbConfig[static::CONFIG_WIDTH], $this->thumbConfig[static::CONFIG_HEIGHT]); $this->imagine->open($origName)->resize($resizeSize)->crop($cropStart, $cropSize)->save($thumbName); } else { copy($origName, $thumbName); } }
/** * {@inheritDoc} */ public function transform($file, array $transformOptions = array(), array $parameters = array()) { $image = $this->imagine->open($file); foreach ($transformOptions as $transform => $args) { if ($transform == 'resize') { $image->resize(new Box($args[0], $args[1])); } else { if ($transform == 'rotate') { list($angle, $background) = array_pad($transformOptions['rotate'], 2, null); $image->rotate((int) $angle, $background); } } } $image->save($file, array('format' => FileUtils::getExtensionFromMime($parameters['mime_type']))); }
public function testResize() { $imagine = new Imagine(); $resizer = new Resizer(); $imageDir = __DIR__ . '/../../test-images'; $target = $imageDir . '/resizedimage1.jpg'; $image = $imagine->open($imageDir . '/testimage1.jpg'); $resizer->resize($image, new Box(100, 200), new FocalPoint(0.5, -1), ImageInterface::FILTER_UNDEFINED); $image->save($target); $image = $imagine->open($target); $size = $image->getSize(); $this->assertEquals(100, $size->getWidth()); $this->assertEquals(200, $size->getHeight()); unlink($target); }
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); }
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 __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); }
public function testGetExceptionWithInvalidWatermarkSize() { $this->setExpectedException('HtImgModule\\Exception\\InvalidArgumentException'); $imagine = new Imagine(); $archos = $imagine->open('resources/Archos.jpg'); $watermark = new Watermark($archos, 'asfd', 'asdf'); }
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)); }
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; }
/** * {@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); }
/** * @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())); }
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 execute() { /** @var $dimensionSettings ImageDimension **/ $dimensionSettings = $this->cropping->getDimension(); // first delete old file $oldFile = sprintf('%s/%s.%s', $this->uploadPath, $this->oldFile->getFileName(), $this->attachment->getExtension()); if (file_exists($oldFile)) { @unlink($oldFile); } /* @var Box */ $size = $this->setBox($dimensionSettings); $originalFile = sprintf('%s/%s.%s', $this->uploadPath, $this->attachment->getName(), $this->attachment->getExtension()); $checkFilename = sprintf('%s/%s.%s', $this->uploadPath, $this->cropping->getFileName(), $this->attachment->getExtension()); if ($this->oldFile->getName() == $this->cropping->getName() && file_exists($checkFilename)) { $cropName = $this->cropping->getFileName(); } else { $fileDuplicateChecker = $this->checkDuplicateFile($this->cropping->getName(), $this->attachment->getExtension()); $cropName = $fileDuplicateChecker['name']; $counter = $fileDuplicateChecker['counter']; $this->cropping->setCounter($counter); } $cropFile = sprintf('%s/%s.%s', $this->uploadPath, $cropName, $this->attachment->getExtension()); $this->imagine->open($originalFile)->crop(new Point($this->x, $this->y), new Box($this->width, $this->height))->save($cropFile); $this->imagine->open($cropFile)->thumbnail($size, ImageInterface::THUMBNAIL_INSET)->save($cropFile); $this->cropping->setFileName($cropName); $this->cropping->setChecksum(sha1_file($cropFile)); $initSize = new MediaFile($cropFile); $this->cropping->setClientHeight($initSize->getHeight()); $this->cropping->setClientWidth($initSize->getWidth()); return $this->cropping; }
/** * @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; }
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 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(); } }
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; } }
/** * 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); }
/** * 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; }
/** * 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); }
/** * 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); }
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']; }
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); }
/** * 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]); }