Ejemplo n.º 1
0
 /**
  * Save the first image result from Google.
  *
  * @param string $query  Search query
  * @param int    $height Resize height
  * @param int    $width  Resize width
  * @param string $path   Path to store the image (will use temp as default)
  *
  * @return System\Models\File|void Created file object
  */
 public static function search($query, $height = 300, $width = 300, $path = null)
 {
     // Prepare the query
     $query = urlencode($query);
     // Prepare path
     $path = $path ?: tempnam(sys_get_temp_dir(), 'image');
     // Use Google Image
     $results = file_get_contents('https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=' . $query);
     if ($results && ($json = json_decode($results, true))) {
         foreach ($json['responseData']['results'] as $image) {
             if (isset($image['url'])) {
                 // Retrive the image
                 $url = $image['url'];
                 $content = @file_get_contents($url);
                 if (!$content) {
                     break;
                 }
                 // Save the image
                 $file_path = $path . basename($url);
                 file_put_contents($file_path, $content);
                 // Resize
                 Resizer::open($file_path)->resize($height, $width)->save($file_path, 100);
                 // Create File object
                 $file = new File();
                 $file->data = $file_path;
                 $file->save();
                 return $file;
             }
         }
     }
 }
Ejemplo n.º 2
0
 /**
  * Tworzy miniaturke i zwraca do niej ścieżkę
  * @param string $file ścieżka do pliku
  * @param array $options szerokość, wysokość, tryb
  * @return string
  */
 public function thumbnail($file, array $options = array())
 {
     $public_path = \App::publicPath();
     if (is_file($public_path . $file)) {
         $fileinfo = pathinfo($file);
         $imagesize = getimagesize($public_path . $file);
         $width = isset($options[0]) ? $options[0] : null;
         $height = isset($options[1]) ? $options[1] : null;
         $mode = isset($options[2]) ? $options[2] : 'landscape';
         $offset = isset($options[3]) ? $options[3] : [0, 0];
         $thumb = $fileinfo['dirname'] . '/thumb_' . $fileinfo['filename'] . '_' . $width . 'x' . $height . '_' . $mode . '.' . $fileinfo['extension'];
         if (file_exists($public_path . $thumb) && !filemtime($public_path . $thumb) <= filemtime($public_path . $file)) {
             $file = $thumb;
         } elseif ($imagesize[0] != $width && ($resizer = Resizer::open($public_path . $file)->resize($width, $height, $mode, $offset))) {
             $resizer->save($public_path . $thumb);
             $file = $thumb;
         }
     }
     return $file;
 }
Ejemplo n.º 3
0
 protected function cropImage($imageSrcPath, $selectionData, $cropSessionKey, $path)
 {
     $originalFileName = basename($path);
     $path = rtrim(dirname($path), '/') . '/';
     $fileName = basename($imageSrcPath);
     if (strpos($fileName, '..') !== false || strpos($fileName, '/') !== false || strpos($fileName, '\\') !== false) {
         throw new SystemException('Invalid image file name.');
     }
     $selectionParams = ['x', 'y', 'w', 'h'];
     foreach ($selectionParams as $paramName) {
         if (!array_key_exists($paramName, $selectionData)) {
             throw new SystemException('Invalid selection data.');
         }
         if (!ctype_digit($selectionData[$paramName])) {
             throw new SystemException('Invalid selection data.');
         }
     }
     $sessionDirectoryPath = $this->getCropSessionDirPath($cropSessionKey);
     $fullSessionDirectoryPath = temp_path($sessionDirectoryPath);
     if (!File::isDirectory($fullSessionDirectoryPath)) {
         throw new SystemException('The image editing session is not found.');
     }
     /*
      * Find the image on the disk and resize it
      */
     $imagePath = $fullSessionDirectoryPath . '/' . $fileName;
     if (!File::isFile($imagePath)) {
         throw new SystemException('The image is not found on the disk.');
     }
     $extension = pathinfo($originalFileName, PATHINFO_EXTENSION);
     $targetImageName = basename($originalFileName, '.' . $extension) . '-' . $selectionData['x'] . '-' . $selectionData['y'] . '-' . $selectionData['w'] . '-' . $selectionData['h'] . '-';
     $targetImageName .= time();
     $targetImageName .= '.' . $extension;
     $targetTmpPath = $fullSessionDirectoryPath . '/' . $targetImageName;
     /*
      * Crop the image, otherwise copy original to target destination.
      */
     if ($selectionData['w'] == 0 || $selectionData['h'] == 0) {
         File::copy($imagePath, $targetTmpPath);
     } else {
         $resizer = Resizer::open($imagePath);
         $resizer->resample($selectionData['x'], $selectionData['y'], $selectionData['w'], $selectionData['h'], $selectionData['w'], $selectionData['h']);
         $resizer->save($targetTmpPath, 95);
     }
     /*
      * Upload the cropped file to the Library
      */
     $targetFolder = $path . 'cropped-images';
     $targetPath = $targetFolder . '/' . $targetImageName;
     $library = MediaLibrary::instance();
     $library->put($targetPath, file_get_contents($targetTmpPath));
     return ['publicUrl' => $library->getPathUrl($targetPath), 'documentType' => MediaLibraryItem::FILE_TYPE_IMAGE, 'itemType' => MediaLibraryItem::TYPE_FILE, 'path' => $targetPath, 'title' => $targetImageName, 'folder' => $targetFolder];
 }
Ejemplo n.º 4
0
 /**
  * Generates and returns a thumbnail path.
  */
 public function getThumb($width, $height, $options = [])
 {
     if (!$this->isImage()) {
         return $this->getPath();
     }
     $width = (int) $width;
     $height = (int) $height;
     $defaultOptions = ['extension' => 'png', 'quality' => 95, 'mode' => 'auto'];
     if (!is_array($options)) {
         $options = ['mode' => $options];
     }
     $options = array_merge($defaultOptions, $options);
     $thumbExt = strtolower($options['extension']);
     $thumbMode = strtolower($options['mode']);
     $thumbFile = 'thumb_' . $this->id . '_' . $width . 'x' . $height . '_' . $thumbMode . '.' . $thumbExt;
     $thumbPath = $this->getStorageDirectory() . $this->getPartitionDirectory() . $thumbFile;
     $thumbPublic = $this->getPublicDirectory() . $this->getPartitionDirectory() . $thumbFile;
     if ($this->hasFile($thumbFile)) {
         return $thumbPublic;
     }
     /*
      * Generate thumbnail
      */
     $resizer = Resizer::open($this->getDiskPath());
     $resizer->resize($width, $height, $options['mode']);
     $resizer->save($thumbPath, $options['quality']);
     return $thumbPublic;
 }
Ejemplo n.º 5
0
 /**
  * Generate the thumbnail based on a remote storage engine.
  */
 protected function makeThumbStorage($thumbFile, $thumbPath, $width, $height, $options)
 {
     $tempFile = $this->getLocalTempPath();
     $tempThumb = $this->getLocalTempPath($thumbFile);
     /*
      * Handle a broken source image
      */
     if (!$this->hasFile($this->disk_name)) {
         BrokenImage::copyTo($tempThumb);
     } else {
         $this->copyStorageToLocal($this->getDiskPath(), $tempFile);
         $resizer = Resizer::open($tempFile);
         $resizer->resize($width, $height, $options['mode'], $options['offset']);
         $resizer->save($tempThumb, $options['quality']);
         FileHelper::delete($tempFile);
     }
     /*
      * Publish to storage and clean up
      */
     $this->copyLocalToStorage($tempThumb, $thumbPath);
     FileHelper::delete($tempThumb);
 }
Ejemplo n.º 6
0
 /**
  * Upload Avatar from Base64 encoded image
  * 
  * @param \RainLab\User\Models\User $user
  * @param string $source
  * string contend of an image on Base64 enconding 
  */
 public static function uploadAvatarFromString($user, $source)
 {
     $dst = '/tmp/avatar_' . $user->getKey() . '_' . uniqid();
     FileHelper::put($dst, base64_decode($source));
     $validImage = true;
     try {
         // Validated is a JPG or PNG
         $imageType = exif_imagetype($dst);
         $validImage = in_array($imageType, [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF]);
         // Validated is not bigger that xx by xx
         if ($validImage) {
             // Test if image is corrupted if OctoberCMS Resizer can open it
             // is more likely the image is ok
             Resizer::open($dst);
             // Test image dimensions
             list($width, $height, $type, $attr) = getimagesize($dst);
             $validImage = $width <= 400 && $height <= 400;
         }
         // Add right file extension to the upload file
         if ($validImage) {
             // Save image with correct image extension
             $extension = [IMAGETYPE_JPEG => 'jpg', IMAGETYPE_PNG => 'png', IMAGETYPE_GIF => 'gif'][$imageType];
             $newDst = $dst . '.' . $extension;
             rename($dst, $newDst);
             $dst = $newDst;
         }
     } catch (\Exception $e) {
         $validImage = false;
     }
     if (!$validImage) {
         throw new \Exception('Must be a valid JPG, GIF or PNG. And not bigger that 400x400 pixels.');
     }
     $file = new File();
     $file->data = $dst;
     $file->is_public = true;
     $file->save();
     if ($file) {
         $user->avatar()->add($file);
     }
 }
Ejemplo n.º 7
0
 protected function cropImage($imageSrcPath, $selectionData, $cropSessionKey, $path)
 {
     $originalFileName = basename($path);
     $path = rtrim(dirname($path), '/') . '/';
     $fileName = basename($imageSrcPath);
     if (strpos($fileName, '..') !== false || strpos($fileName, '/') !== false || strpos($fileName, '\\') !== false) {
         throw new SystemException('Invalid image file name.');
     }
     $selectionParams = ['x', 'y', 'w', 'h'];
     foreach ($selectionParams as $paramName) {
         if (!array_key_exists($paramName, $selectionData)) {
             throw new SystemException('Invalid selection data.');
         }
         if (!ctype_digit($selectionData[$paramName])) {
             throw new SystemException('Invalid selection data.');
         }
     }
     $sessionDirectoryPath = $this->getCropSessionDirPath($cropSessionKey);
     $fullSessionDirectoryPath = temp_path($sessionDirectoryPath);
     if (!File::isDirectory($fullSessionDirectoryPath)) {
         throw new SystemException('The image editing session is not found.');
     }
     // Find the image on the disk and resize it
     $imagePath = $fullSessionDirectoryPath . '/' . $fileName;
     if (!File::isFile($imagePath)) {
         throw new SystemException('The image is not found on the disk.');
     }
     $extension = pathinfo($originalFileName, PATHINFO_EXTENSION);
     $targetImageName = basename($originalFileName, '.' . $extension) . '-' . $selectionData['x'] . '-' . $selectionData['y'] . '-' . $selectionData['w'] . '-' . $selectionData['h'] . '-';
     $targetImageName .= time();
     $targetImageName .= '.' . $extension;
     $targetTmpPath = $fullSessionDirectoryPath . '/' . $targetImageName;
     if ($selectionData['w'] == 0 || $selectionData['h'] == 0) {
         // If cropping is not required, copy the oiginal image to the target destination.
         File::copy($imagePath, $targetTmpPath);
     } else {
         $resizer = Resizer::open($imagePath);
         $resizer->resample($selectionData['x'], $selectionData['y'], $selectionData['w'], $selectionData['h'], $selectionData['w'], $selectionData['h']);
         $resizer->save($targetTmpPath, 95);
     }
     // Upload the cropped file to the Library
     $targetPath = $path . 'cropped-images/' . $targetImageName;
     $library = MediaLibrary::instance();
     $library->put($targetPath, file_get_contents($targetTmpPath));
     return $library->getPathUrl($targetPath);
 }