2016-04-05 4 views
1

Я пытаюсь добавить текст к изображению с границей перед загрузкой на сервер. Кажется, однако, что я написал свой код, не загружает изображение. Я проверил отдельно, что работа загружать и манипуляцию изображений работа, но вместе они не работают:Редактирование изображения с GD перед загрузкой на сервер

$name = "some text"; 
$target_dir = "uploads/"; 
//strip filename of clear spaces 
$cleaned = str_replace(' ', '', basename($_FILES["fileToUpload"]["name"])); 
$target_file = $target_dir . $cleaned; 
$image = $_FILES["fileToUpload"]["name"]; 


$im = imagecreatefromjpeg($image); 
$white = imagecolorallocate($im, 255, 255, 255); 
$font_path = 'uploads/SCRIPTIN.ttf'; 
$text = "In Memory of " . $name; 
imagesetthickness($im, 200); 
$black = imagecolorallocate($im, 0, 0, 0); 
$x = 0; 
$y = 0; 
$w = imagesx($im) - 1; 
$z = imagesy($im) - 1; 
imageline($im, $x, $y, $x, $y+$z, $black); 
imageline($im, $x, $y, $x+$w, $y, $black); 
imageline($im, $x+$w, $y, $x+$w, $y+$z, $black); 
imageline($im, $x, $y+$z, $x+$w ,$y+$z, $black); 
imagettftext($im, 200, 0, 20, 300, $white, $font_path, $text); 

Я думаю, что это может быть связанно с тем, как я пишу файл на сервер:

move_uploaded_file(imagejpeg($im), $target_file); 
+0

Вы должны использовать $ _FILES [ 'fileToUpload'] ['tmp_name'], где файл фактически хранится на вашем сервере, $ _FILES ['fileToUpload'] ['name'] дает только исходное имя, как это было на компьютере пользователя. Кроме того, вы не выполняете никаких проверок относительно того, является ли это допустимым файлом - это может привести к проблемам, вы не должны доверять своему пользователю. По крайней мере, выполните проверку расширения и проверку типа mime. Это также позволит вам работать с форматами изображений, отличными от jpg/jpeg. – Eihwaz

+0

просто замените «move_uuploaded_file» на «imagejpeg ($ im, $ target_file);» – kraysak

ответ

1

Это быстрый проект, но он должен работать:

Создайте файл ImageProcessor.php, скопируйте код и включить его с помощью require_once:

class ImageProcessor 
{ 
    /** @var string actual file, in our tmp folder on the server */ 
    private $file; 

    /** @var string filename that we are going to save it with */ 
    private $filename; 

    /** @var string the name we are going to write on the image */ 
    private $name_to_write; 

    /** @var resource file resource */ 
    private $resource = false; 

    /** @var string where we are going to save the result */ 
    public static $save_path = 'images/'; 

    /** @var array the list of file extensions we're going to allow */ 
    private $allowed_extensions = array('jpg', 'jpeg', 'png', 'gif'); 

    public function __construct($file, $name_to_write) 
    { 
     if (!is_array($file) || !isset($file['tmp_name'])) { 
      throw new Exception('We are expecting something else'); 
     } 

     $this->file = $file['tmp_name']; 
     $this->filename = $file['name']; 
     $this->name_to_write = $name_to_write; 

     if (!$this->checkFileValidity()) { 
      throw new Exception('Invalid file'); 
     } 
    } 

    /* 
    * Get the file extension in lowercase for further checks 
    * 
    * @return string 
    */ 
    private function getExtension() 
    { 
     return strtolower(pathinfo($this->filename, PATHINFO_EXTENSION)); 
    } 

    /* 
    * Check whether the file has a valid extension. 
    * 
    * @return bool 
    */ 
    private function checkFileValidity() 
    { 
     return in_array($this->getExtension(), $this->allowed_extensions); 
    } 

    /* 
    * Create a resource, depending on file's extension 
    * 
    * @return void 
    */ 
    private function setFileResource() 
    { 
     switch ($this->getExtension()) { 
      case 'jpeg': 
      case 'jpg': 
       $this->resource = imagecreatefromjpeg($this->file); 
      break; 

      case 'png': 
       $this->resource = imagecreatefrompng($this->file); 
      break; 

      case 'gif': 
       $this->resource = imagecreatefromgif($this->file); 
      break; 
     } 
    } 

    /* 
    * Process the file - add borders, and writings, and so on. 
    * In the last step we're also saving it. 
    * 
    * @return void 
    */ 
    public function processFile() 
    { 
     $this->setFileResource(); 

     if (!$this->resource) { 
      throw new Exception('Invalid file'); 
     } 

     $white = imagecolorallocate($this->resource, 255, 255, 255); 
     $font_path = 'uploads/SCRIPTIN.ttf'; 
     $text = "In Memory of ".$this->name_to_write; 

     imagesetthickness($this->resource, 200); 
     $black = imagecolorallocate($this->resource, 0, 0, 0); 
     $x = 0; 
     $y = 0; 
     $w = imagesx($im) - 1; 
     $z = imagesy($im) - 1; 
     imageline($this->resource, $x, $y, $x, $y+$z, $black); 
     imageline($this->resource, $x, $y, $x+$w, $y, $black); 
     imageline($this->resource, $x+$w, $y, $x+$w, $y+$z, $black); 
     imageline($this->resource, $x, $y+$z, $x+$w ,$y+$z, $black); 
     imagettftext($this->resource, 200, 0, 20, 300, $white, $font_path, $text); 

     return $this->save(); 
    } 

    /* 
    * Save the file in $save_path and return the path to the file 
    * 
    * @return mixed string|bool 
    */ 
    private function save() 
    { 
     imagejpeg($this->resource, self::$save_path.$this->filename); 

     return file_exists(self::$save_path.$this->filename) ? self::$save_path.$this->filename : false; 
    } 
} 

И тогда вы это называете, когда вы обнаружили, что файл был загружен:

if (isset($_FILES['fileToUpload']) && is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) { 
    $processor = new ImageProcessor($_FILES['fileToUpload'], 'John Doe'); 

    if ($image_path = $processor->processFile()) { 
     var_dump($image_path); // this is your new image 
    } 
} 

ОБНОВЛЕНО (забыл включить имя написать на изображении)

Смежные вопросы