public function fit_to_width($width, $upscale = false)
 {
     if ($upscale === false && $width >= $this->image_class->get_width()) {
         return $this;
     }
     $this->image_class->fit_to_width($width);
     return $this;
 }
示例#2
0
 public function upload_image($image, $properties)
 {
     // Filename
     $random_string = $properties['filename'] . '-' . str_replace(' ', '_', $image['name']);
     // Initialise SimpleImage
     $img = new SimpleImage($image['tmp_name']);
     // Get Properties
     $max_width = $properties['max_width'];
     // Check for min width
     if (isset($properties['min_width'])) {
         if ($img->get_width() < $properties['min_width']) {
             return false;
         }
     }
     // Resize image
     try {
         $img->fit_to_width($max_width);
         $img->save($this->upload_folder . '/' . $random_string);
         // Save the image to the_image
         $this->the_image = $this->public_folder . '/' . $random_string;
     } catch (Exception $e) {
         echo $e->getMessage();
         // In a production app, the error should be logged or
         // sent to your own error handler/alert system and not
         // echoed out.
     }
     // Check to see if we need to generate thumbnail
     if (isset($properties['thumbnail'])) {
         // Get Properties
         $thumb_width = $properties['thumbnail']['width'];
         $thumb_height = $properties['thumbnail']['height'];
         // Generate thumbnail
         try {
             $img->adaptive_resize($thumb_width, $thumb_height);
             $img->save($this->upload_folder . '/thumbnails/' . $random_string);
             // Save the image to the_thumbnail
             $this->the_thumbnail = $this->public_folder . '/thumbnails/' . $random_string;
         } catch (Exception $e) {
             echo $e->getMessage();
         }
     }
 }
 /**
  * @param string $source
  * @param array $options
  * @return bool|mixed
  */
 protected function resizeImage($source, $options)
 {
     try {
         $cachepath = $this->getCachePath($source, $options);
         if (!file_exists($cachepath)) {
             $image = new SimpleImage(App::path() . '/' . $source);
             if (!empty($options['width']) && empty($options['height'])) {
                 $image->fit_to_width($options['width']);
             }
             if (!empty($options['height']) && empty($options['width'])) {
                 $image->fit_to_height($options['height']);
             }
             if (!empty($options['height']) && !empty($options['width'])) {
                 $image->thumbnail($options['width'], $options['height']);
             }
             $image->save($cachepath);
         }
         return trim(str_replace(App::path(), '', $cachepath), '/');
     } catch (\Exception $e) {
         return false;
     }
 }
示例#4
0
文件: Image.php 项目: ejailesb/repo
 /**
  * @return SimpleImage
  */
 protected function create()
 {
     $image = new SimpleImage($this->file);
     switch ($this->options['strategy']) {
         case 'thumbnail':
             $width = $this->options['w'] ?: $image->get_width();
             $height = $this->options['h'] ?: $image->get_height();
             $image->resize($width, $height);
             break;
         case 'best_fit':
             $width = $this->options['w'] ?: $image->get_width();
             $height = $this->options['h'] ?: $image->get_height();
             if (is_numeric($width) && is_numeric($height)) {
                 $image->best_fit($width, $height);
             }
             break;
         default:
             $width = $this->options['w'];
             $height = $this->options['h'];
             if (is_numeric($width) && is_numeric($height)) {
                 $image->thumbnail($width, $height);
             } elseif (is_numeric($width)) {
                 $image->fit_to_width($width);
             } elseif (is_numeric($height)) {
                 $image->fit_to_height($height);
             } else {
                 $width = $image->get_width();
                 $height = $image->get_height();
                 $image->thumbnail($width, $height);
             }
     }
     return $image;
 }
示例#5
0
 /**
  * @param string $source
  * @param array $options
  * @return bool|mixed
  */
 protected function resizeImage($source, $options)
 {
     try {
         $image_path = App::locator()->get($source);
         $cachepath = $this->getCachePath($image_path, $options);
         if (!file_exists($cachepath)) {
             $image = new SimpleImage($image_path);
             if (!empty($options['width']) && empty($options['height'])) {
                 $image->fit_to_width($options['width']);
             }
             if (!empty($options['height']) && empty($options['width'])) {
                 $image->fit_to_height($options['height']);
             }
             if (!empty($options['height']) && !empty($options['width'])) {
                 $image->thumbnail($options['width'], $options['height']);
             }
             $image->save($cachepath);
         }
         return $this->basePath($cachepath);
     } catch (\Exception $e) {
         return false;
     }
 }
示例#6
0
文件: Utils.php 项目: Apretaste/Core
 /**
  * Reduce image size and optimize the image quality
  *
  * @author salvipascual
  * @author kuma
  * @version 2.0
  * @param String $imagePath, path to the image
  * @param number $width Fit to width
  * @param number $height Fit to height
  * @param number $quality Decrease/increase quality
  * @param string $format Convert to format
  * @return boolean
  */
 public function optimizeImage($imagePath, $width = "", $height = "", $quality = 70, $format = 'image/jpeg')
 {
     if (!class_exists('SimpleImage')) {
         include_once "../lib/SimpleImage.php";
     }
     try {
         $img = new SimpleImage();
         $img->load($imagePath);
         if (!empty($width)) {
             $img->fit_to_width($width);
         }
         if (!empty($height)) {
             $img->fit_to_height($height);
         }
         $img->save($imagePath, $quality, $format);
     } catch (Exception $e) {
         return false;
     }
     return true;
 }
示例#7
0
 /**
  * Main processing script
  *
  * @throws Exception
  */
 public function processAction()
 {
     $this->view->disable();
     if ($this->request->isAjax()) {
         // Set transaction manager
         $transactionManager = new TransactionManager();
         $transaction = $transactionManager->get();
         $root = $this->root;
         $upload_dir_full = $this->upload_dir_full;
         $processed_dir = $this->processed_dir;
         // Create processed folder if it doesn't exist
         if (!file_exists($processed_dir)) {
             mkdir($processed_dir, 0777, true);
         }
         $qrs = $this->persistent->qrs;
         $errors = $this->persistent->errors;
         $created_prods_counter = $this->persistent->created_prods_counter;
         $created_prods_ids = $this->persistent->created_prods_ids;
         $id = $this->request->get('id');
         $item = self::filter($upload_dir_full, "{$id}")[$id];
         // A product must have a minimum of 3 photos
         if (count($item, true) - 1 < 4) {
             $this->errorExit($errors, $id, "У товара должно быть минимум три фотографии!");
         }
         // Check for file name (should not contain alphabetic characters)
         foreach ($item as $i => $f) {
             if (preg_match_all('/[A-Za-z]+\\d*\\./', "{$upload_dir_full}/{$f}")) {
                 $this->errorExit($errors, $id, "Неправильное название файла ({$f})");
             }
         }
         // QR code image
         $qrcode_img = $item[0];
         // Get scanned QR code
         if ($qrs[$id] != false) {
             $code = $qrs[$id];
         } else {
             $this->errorExit($errors, $id, "Не удалось отсканировать QR код ({$qrcode_img})");
         }
         // Check for product existence
         if (PProductMain::findFirst($code)) {
             $this->errorExit($errors, $id, "Товар с таким QR кодом уже внесен в базу ({$code})");
         }
         // -----------------------------------------------------------
         // QR code processing
         $qrcode_info = pathinfo($qrcode_img);
         $qrcode_name = "{$qrcode_info['filename']}qr{$code}";
         $qrcode_folder = rand(111, 999) . "/" . rand(1111111, 99999999) . "/";
         $width = getimagesize("{$upload_dir_full}/{$qrcode_img}")[0];
         $height = getimagesize("{$upload_dir_full}/{$qrcode_img}")[1];
         $filesize = filesize("{$upload_dir_full}/{$qrcode_img}");
         // Create folders for a QR code
         mkdir($root . $this->config->upload->media_qrcodeimage_folder . "/" . $qrcode_folder, 0777, true);
         mkdir($root . $this->config->upload->media_qrcodeimage_nail_folder . "/" . $qrcode_folder, 0777, true);
         // Copy QR code image to the respective folder
         if (!copy("{$upload_dir_full}/{$qrcode_img}", $root . $this->config->upload->media_qrcodeimage_folder . "/" . $qrcode_folder . $qrcode_name . "." . $qrcode_info['extension'])) {
             $this->errorExit($errors, $id, "Ошибка при копировании изображения QR кода ({$qrcode_img})");
         }
         $qrimg = new SimpleImage("{$upload_dir_full}/{$qrcode_img}");
         // Resize QR code image for a thumbnail (100 px) and copy it to nail folder
         if (!$qrimg->fit_to_width(100)->save($root . $this->config->upload->media_qrcodeimage_nail_folder . "/" . $qrcode_folder . $qrcode_name . "." . $qrcode_info['extension'])) {
             $this->errorExit($errors, $id, "Ошибка при копировании изображения (nail) QR кода ({$qrcode_img})");
         }
         // Add QR code to the db
         $qrcode = new PProdQrcodeimage();
         $qrcode->setTransaction($transaction);
         $qrcode->product_id = $code;
         $qrcode->uri = $qrcode_name;
         $qrcode->ext = $qrcode_info['extension'];
         $qrcode->width = $width;
         $qrcode->height = $height;
         $qrcode->filesize = $filesize;
         $qrcode->folder = $qrcode_folder;
         $qrcode->thumbnail = "/thumb/qrcodeimage/nail/{$qrcode_folder}{$qrcode_name}.{$qrcode_info['extension']}";
         $qrcode->ordered = $qrcode->ordered();
         $qrcode->created = time();
         $qrcode->updated = time();
         if (!$qrcode->create()) {
             $transactionManager->collectTransactions();
             // Clear transactions
             $this->errorExit($errors, $id, "Ошибка при добавлении QR кода в базу данных ({$qrcode_img})");
         }
         // Remove QR code from the array
         array_shift($item);
         // -----------------------------------------------------------
         // Photos processing
         $photo_counter = 1;
         foreach ($item as $img) {
             // A product can have a maximum of 5 photos
             if ($photo_counter > 5) {
                 break;
             }
             // Change photo orientation if needed
             //                self::changeOrientation("$upload_dir_full/$img");
             $img_info = pathinfo($img);
             $rand = rand(1111, 9999);
             $width = getimagesize("{$upload_dir_full}/{$img}")[0];
             $height = getimagesize("{$upload_dir_full}/{$img}")[1];
             $filesize = filesize("{$upload_dir_full}/{$img}");
             $img_name = "IMG_{$rand}_{$height}";
             $img_folder = rand(111, 999) . "/" . rand(1111111, 99999999) . "/";
             // Create folders
             mkdir($root . $this->config->upload->media_productphoto_folder . "/" . $img_folder, 0777, true);
             mkdir($root . $this->config->upload->media_productphoto_thumb_folder . "/" . $img_folder, 0777, true);
             mkdir($root . $this->config->upload->media_productphoto_nail_folder . "/" . $img_folder, 0777, true);
             // Resave an image to remove EXIF data
             if (self::removeExif("{$upload_dir_full}/{$img}") == false) {
                 $this->errorExit($errors, $id, "Ошибка при обработке фотографии ({$img})");
             }
             // Copy an image to the respective folder
             if (!copy("{$upload_dir_full}/{$img}", $root . $this->config->upload->media_productphoto_folder . "/" . $img_folder . $img_name . "." . $img_info['extension'])) {
                 $this->errorExit($errors, $id, "Ошибка при копировании фотографии ({$img})");
             }
             // Resize an image for a thumbnail (500 px) and copy it to thumb folder
             $thumb_img = new SimpleImage("{$upload_dir_full}/{$img}");
             if (!$thumb_img->fit_to_width(500)->save($root . $this->config->upload->media_productphoto_thumb_folder . "/" . $img_folder . $img_name . "." . $img_info['extension'])) {
                 $this->errorExit($errors, $id, "Ошибка при копировании фотографии (thumb) ({$img})");
             }
             // Resize an image for a thumbnail (100 px) and copy it to nail folder
             $nail_img = new SimpleImage("{$upload_dir_full}/{$img}");
             if (!$nail_img->fit_to_width(100)->save($root . $this->config->upload->media_productphoto_nail_folder . "/" . $img_folder . $img_name . "." . $img_info['extension'])) {
                 $this->errorExit($errors, $id, "Ошибка при копировании фотографии (nail) ({$img})");
             }
             // Add image to the db
             $imgdb = new PProdPhoto();
             $imgdb->setTransaction($transaction);
             $imgdb->uri = $img_name;
             $imgdb->ext = $img_info['extension'];
             $imgdb->width = $width;
             $imgdb->height = $height;
             $imgdb->filesize = $filesize;
             $imgdb->folder = $img_folder;
             $imgdb->thumbnail = "/thumb/productphoto/nail/{$img_folder}{$img_name}.{$img_info['extension']}";
             $imgdb->product_id = $code;
             $imgdb->ordered = $photo_counter;
             $imgdb->created = time();
             $imgdb->updated = time();
             if (!$imgdb->create()) {
                 $transactionManager->collectTransactions();
                 // Clear transactions
                 $this->errorExit($errors, $id, "Ошибка при добавлении фотографий в базу данных ({$img})");
             }
             $photo_counter++;
         }
         // Create a new product
         $product = new PProductMain();
         $product->setTransaction($transaction);
         $product->id = $code;
         $product->created = time();
         $product->updated = time();
         $product->new = 1;
         $product->hasphoto = 1;
         $product->qrcodeimage_id = $qrcode->id;
         $product->status = 0;
         if (!$product->create()) {
             $transactionManager->collectTransactions();
             // Clear transactions
             $this->errorExit($errors, $id, "Ошибка при создании товара (QR - {$code})");
         }
         // Complete the transaction
         if (!$transaction->commit()) {
             $this->errorExit($errors, $id, "Ошибка транзакции (QR - {$code})");
         }
         // Set stats
         $this->ProdInfoService->setStat('product_created', 'photoUploader', 'ru', $code);
         // Move QR code image
         rename("{$upload_dir_full}/{$qrcode_img}", "{$processed_dir}/{$qrcode_name}.{$qrcode_info['extension']}");
         // Clear thumb for QR code img
         //            if (file_exists("$upload_dir_full/thumbs/$qrcode_img")) unlink("$upload_dir_full/thumbs/$qrcode_img");
         foreach ($item as $img) {
             // Move images
             rename("{$upload_dir_full}/{$img}", "{$processed_dir}/{$img}");
             // Clear thumbs
             //                if (file_exists("$upload_dir_full/thumbs/$img")) unlink("$upload_dir_full/thumbs/$img");
         }
         // Remove the id from QRs list
         $qrs = $this->persistent->qrs;
         unset($qrs[$id]);
         // Update counter and list of ids
         $created_prods_counter++;
         $created_prods_ids[] = $code;
         $this->persistent->qrs = $qrs;
         $this->persistent->created_prods_counter = $created_prods_counter;
         $this->persistent->created_prods_ids = $created_prods_ids;
         // Hooray!
         echo "success";
     }
 }