Advertisement
EvenGuy

Олимпиада по PHP [Задание B]

Feb 10th, 2017
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 5.05 KB | None | 0 0
  1. <?php
  2.     // Стандартный файл с входными данными - in.txt
  3.     // Выходной файл изображения имеет о же имя что и оригинальное изображение, с приставкой out_
  4.     // Т.е. test.jpg -> out_test.jpg
  5.  
  6.     class ImgMod {
  7.         private $filePath;
  8.        
  9.         private $imgFilePath;
  10.         private $imgEffect;
  11.            
  12.         private $imgPtr;
  13.         private $imgType; // Может быть 'png' или 'jpg'
  14.        
  15.         // Конструктор класса
  16.         // По-умолчанию имя входного файла(текстового) - in.txt
  17.         function __construct($filePath = 'in.txt') {
  18.             $this->filePath = $filePath;
  19.            
  20.             // Считывание входных данных из файла и загрузка изображения
  21.             try {
  22.                 $this->loadDataFromFile();
  23.                 $this->loadImg();
  24.             } catch (Exception $e) {
  25.                 echo 'При считывании данных возникла ошибка: '.$e->GetMessage();
  26.                 exit;
  27.             }
  28.            
  29.             // Применение эффекта
  30.             try {
  31.                 $this->applyEffect();
  32.             } catch (Exception $e) {
  33.                 echo 'Во время применения эффекта возникла ошибка: '.$e->GetMessage();
  34.                 exit;
  35.             }
  36.            
  37.             // Сохранение измененного изображения
  38.             try {
  39.                 $this->saveImg();
  40.             } catch (Exception $e) {
  41.                 echo 'При сохранении возникла ошибка: '.$e->GetMessage();
  42.                 exit;
  43.             }
  44.            
  45.             imagedestroy($this->imgPtr);
  46.         }
  47.        
  48.         // Считывание данных из файла
  49.         private function loadDataFromFile() {
  50.             // Определение наличия файла
  51.             if ( !file_exists($this->filePath) )
  52.                 throw new Exception('Не найден файл '.$this->filePath);
  53.            
  54.             // Считывание данных
  55.             $fileDataArr = file($this->filePath);
  56.            
  57.             $this->imgFilePath = trim($fileDataArr[0]);
  58.             $this->imgEffect = trim($fileDataArr[1]);
  59.         }
  60.        
  61.         // Загрузка изображения
  62.         private function loadImg() {
  63.             // Определение наличия файла изображения
  64.             if ( !file_exists($this->imgFilePath) )
  65.                 throw new Exception('Не найден файл '.$this->imgFilePath);
  66.            
  67.             // Загрузка изображения
  68.             $this->getImgType();           
  69.             switch($this->imgType) {
  70.                 case 'png':
  71.                     $this->imgPtr = imagecreatefrompng($this->imgFilePath);
  72.                     break;
  73.                 case 'jpg':
  74.                     $this->imgPtr = imagecreatefromjpeg($this->imgFilePath);
  75.                     break;
  76.                 default:
  77.                     throw new Exception('Неизвестный тип избражения - '.$this->imgType);
  78.                     break;
  79.             }
  80.         }
  81.        
  82.         // Определение типа изображения по расширению
  83.         private function getImgType() {
  84.             $fileNameArr = explode('.',$this->imgFilePath);
  85.             if (count($fileNameArr) < 2)
  86.                 throw new Exception('Не задано расширение файла '.$this->imgFilePath);
  87.            
  88.             $fileType = trim(strtolower($fileNameArr[count($fileNameArr)-1]));
  89.             if ( ($fileType != 'png') && ($fileType != 'jpg') && ($fileType != 'jpeg') )
  90.                 throw new Exception('Неизвестный тип файла - '.$fileType);
  91.            
  92.             if ( $fileType == 'jpeg' )
  93.                 $fileType = 'jpg';
  94.            
  95.             $this->imgType = $fileType;
  96.         }
  97.        
  98.         // Применение эффекта к изображению
  99.         private function applyEffect() {
  100.             switch($this->imgEffect) {
  101.                 // Размытие
  102.                 case 'blur':
  103.                     imagefilter($this->imgPtr, IMG_FILTER_SMOOTH,0);
  104.                     imagefilter($this->imgPtr, IMG_FILTER_GAUSSIAN_BLUR);
  105.                     break;
  106.                 // Негатив
  107.                 case 'negative':
  108.                     imagefilter($this->imgPtr, IMG_FILTER_NEGATE);
  109.                     break;
  110.                 // Градации серого
  111.                 case 'gray':
  112.                     imagefilter($this->imgPtr, IMG_FILTER_GRAYSCALE);
  113.                     break;
  114.                 // Отражение по-горизонтали
  115.                 case 'mirror':
  116.                     $imgSizeX = imagesx($this->imgPtr);
  117.                     $imgSizeY = imagesy($this->imgPtr);
  118.                    
  119.                     $mirrImg = imagecreatetruecolor($imgSizeX,$imgSizeY);
  120.                    
  121.                     for($y = 0; $y < $imgSizeY; $y++) {
  122.                         for($x = 0; $x < $imgSizeX; $x++) {
  123.                             imagesetpixel($mirrImg,$x,$y,
  124.                                           imagecolorat($this->imgPtr,($imgSizeX-$x-1),$y));
  125.                         }
  126.                     }
  127.                    
  128.                     imagedestroy($this->imgPtr);
  129.                     $this->imgPtr = $mirrImg;
  130.                    
  131.                     break;
  132.                 // Незивестный эффект
  133.                 default:
  134.                     throw new Exception('Неизвестный эффект - '.$this->imgEffect);
  135.                     break;
  136.             }
  137.         }
  138.        
  139.         // Сохранение изображения в файл
  140.         private function saveImg() {
  141.             $newImgFileName = dirname($this->imgFilePath).'/out_'.basename($this->imgFilePath);        
  142.             switch($this->imgType) {
  143.                 case 'jpg':
  144.                     imagejpeg($this->imgPtr,$newImgFileName);
  145.                     break;
  146.                 case 'png':
  147.                     imagepng($this->imgPtr,$newImgFileName);
  148.                     break;
  149.                 default:
  150.                     throw new Exception('Неизвестный тип файла - '.$this->imgType);
  151.                     break;
  152.             }
  153.         }
  154.     }
  155.    
  156.     $oImgMod = new ImgMod();
  157. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement