PHP создавать эскизы и объединять их? - PullRequest
0 голосов
/ 20 октября 2018

Я делаю приложение, в котором пользователи могут публиковать фотографии, и мне нужно создать для них предварительный просмотр.

Вот так: enter image description here

Мне нужно конечное уменьшенное изображение размером 500px300px.

Если изображения обрезаются, не проблема, важно только, чтобы они были одинаковой ширины и высоты и чтобы они были заполненывсе место.

Это мой код:

if(count($_FILES['image']['name']) > 0) {

  $imagesCount = count($_FILES['image']['name']);
  if ($imagesCount > $maxFilesNum - $usedFilesNum) {
      exit("Too many files!");
  }

  for($i=0; $i<$imagesCount; $i++){

    $imgname=$_FILES['image']['name'][$i];
    $imgloc=$_FILES['image']['tmp_name'][$i];
    if ($imgname == NULL || $imgloc == NULL){

        exit("Error1");
    }

    $path_parts = pathinfo($imgname);
    $ext = $path_parts['extension'];
    if ($ext != "png" && $ext != "jpg" && $ext != "gif" && $ext != "jpge"){
        exit("Error2");
   }

    // thumbnail

    $image = new SimpleImage();
    $image->load($imgloc);
    $imageThumbnail = $image;
    $imageThumbnail->resizeToHeight(300);

    $uniqueId = uniqid();
    $fileName = $lastInsertedId . "_" . $i . $uniqueId . "." . $ext;

    if(!move_uploaded_file($imgloc, "../../resources/img/posts/" . $fileName)){
        exit("Error3");
    }

    $file_names []= $fileName;
    $file_thumbnails []= $imageThumbnail;

  }
}

$mergedImages = new SimpleImage();
$mergedImages->mergeImages($file_thumbnails);


if(!move_uploaded_file($mergedImages, "../../resources/img/posts/prev/". $lastInsertedId . ".png")){
  exit("Error4");
}

И класс SimpleImages:

class SimpleImage {

   var $image;
   var $image_type;

   function load($filename) {

      $image_info = getimagesize($filename);
      $this->image_type = $image_info[2];
      if( $this->image_type == IMAGETYPE_JPEG ) {

         $this->image = imagecreatefromjpeg($filename);
      } elseif( $this->image_type == IMAGETYPE_GIF ) {

         $this->image = imagecreatefromgif($filename);
      } elseif( $this->image_type == IMAGETYPE_PNG ) {

         $this->image = imagecreatefrompng($filename);
      }
   }
   function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {

      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image,$filename,$compression);
      } elseif( $image_type == IMAGETYPE_GIF ) {

         imagegif($this->image,$filename);
      } elseif( $image_type == IMAGETYPE_PNG ) {

         imagepng($this->image,$filename);
      }
      if( $permissions != null) {

         chmod($filename,$permissions);
      }
   }
   function output($image_type=IMAGETYPE_JPEG) {

      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image);
      } elseif( $image_type == IMAGETYPE_GIF ) {

         imagegif($this->image);
      } elseif( $image_type == IMAGETYPE_PNG ) {

         imagepng($this->image);
      }
   }
   function getWidth() {

      return imagesx($this->image);
   }
   function getHeight() {

      return imagesy($this->image);
   }
   function resizeToHeight($height) {

      $ratio = $height / $this->getHeight();
      $width = $this->getWidth() * $ratio;
      $this->resize($width,$height);
   }

   function resizeToWidth($width) {
      $ratio = $width / $this->getWidth();
      $height = $this->getheight() * $ratio;
      $this->resize($width,$height);
   }

   function scale($scale) {
      $width = $this->getWidth() * $scale/100;
      $height = $this->getheight() * $scale/100;
      $this->resize($width,$height);
   }

   function resize($width,$height) {
      $new_image = imagecreatetruecolor($width, $height);
      imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
      $this->image = $new_image;
   }      

   function mergeImages($images) {
    $mergedImageFinalPath;
    for ($i = 0; $i <= count($images)-2; $i++){
        $img1_path;
        if ($i > 0){
            $img1_path = $mergedImageFinalPath;
        } else {
            $img1_path = $images[0];
        }
        $img2_path = $images[$i+1];



        list($img1_width, $img1_height) = getimagesize($img1_path);
        list($img2_width, $img2_height) = getimagesize($img2_path);

        $merged_width  = $img1_width + $img2_width;
        //get highest
        $merged_height = $img1_height > $img2_height ? $img1_height : $img2_height;

        $merged_image = imagecreatetruecolor($merged_width, $merged_height);

        imagealphablending($merged_image, false);
        imagesavealpha($merged_image, true);

        $img1 = imagecreatefrompng($img1_path);
        $img2 = imagecreatefrompng($img2_path);

        imagecopy($merged_image, $img1, 0, 0, 0, 0, $img1_width, $img1_height);
        //place at right side of $img1
        imagecopy($merged_image, $img2, $img1_width, 0, 0, 0, $img2_width, $img2_height);

        $mergedImageFinalPath = $merged_image;
    }

    return imagepng($mergedImageFinalPath);
    imagedestroy($mergedImageFinalPath);
   }
}

Кто-нибудь может мне помочь?Я не могу заставить это работать:

$mergedImages->mergeImages($file_thumbnails);

часть, кажется, действительно не работает ..

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...