Как загрузить изображение и создать миниатюру одновременно в PHP?

#php #thumbnails

Вопрос:

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

cropimage.php:

 <?php
class Crop
{
    public $img_name;
    public $tmp_img_name;
    public $folder;
    public $ext;
    public $new_name;


    function CropImage($file, $max_resolution)
    {

        if (file_exists($file)) {
            $original_image = imagecreatefromjpeg($file);
            $original_width = imagesx($original_image);
            $original_height = imagesy($original_image);

            //Try max-width first
            if ($original_height > $original_width) {

                $ratio = $max_resolution / $original_width;
                $new_width = $max_resolution;
                $new_height = $original_height * $ratio;
            } else {

                $ratio = $max_resolution / $original_height;
                $new_height = $max_resolution;
                $new_width = $original_width * $ratio;
            }

            if ($original_image) {

                $new_image = imagecreatetruecolor($new_width, $new_height);
                imagecopyresampled($new_image, $original_image, 0, 0, 0, 0, $new_width, $new_height, $original_width, $original_height);

                $new_crop_image = imagecreatetruecolor($max_resolution, $max_resolution);
                imagecopyresampled($new_crop_image, $new_image, 0, 0, 0, 0, $max_resolution, $max_resolution, $max_resolution, $max_resolution);

                imagejpeg($new_crop_image, $file, 90);
            }
        }
    }


    public function RunCrop()
    {
        $thumb_name_name = $this->img_name;
        $thumb_tmp_name = $this->tmp_img_name;
        $thumb_new_name = $this->new_name;
        $thumb_folder = "../public/assets/uploadThumb/";
        $file = $thumb_folder . $thumb_new_name;

        //Copy the original image to thumb folder
        copy($this->folder . $this->new_name, $file);

        //Resize file
        $this->CropImage($file, "300");
    }
}
 

saveimage.php:

 <?php

include "../app/core/config.php";
include "../app/core/cropImage.php";

class UploadImage
{
    private $ext = "";
    private $new_name = "";
    private $save_result = 0;

    public function UploadIMG()
    {
        if (isset($_POST['img_submit'])) {
            try {

                //For uploading original image
                $crop = new Crop();

                $crop->img_name = $_FILES['image']['name'];
                $crop->tmp_img_name = $_FILES['image']['tmp_name'];
                $crop->folder = "../public/assets/img/";
                //For finding file extension
                $crop->ext = pathinfo($crop->img_name, PATHINFO_EXTENSION);
                //Renaming the uploaded file
                $crop->new_name = $this->RandomStringGenerator() . "." . $crop->ext;
                $this->new_name = $crop->new_name;
                //Moving to the desired path
                move_uploaded_file($crop->tmp_img_name, $crop->folder . $crop->new_name);
                $this->RegisterIntoDatabase();

                //For cropping image and creating thumbnail
                $crop->RunCrop();

                unset($_POST);
                $this->save_result = 1;
                return $this->save_resu<
            } catch (Throwable $th) {

                $this->save_result = 2;
                return $this->save_resu<
            }
        }
    }
    public function RandomStringGenerator()
    {
        $permitted_chars = "0123456789abcdefghijkl";
        $random_string = substr(str_shuffle($permitted_chars), 0, 10);
        return $random_string;
    }
    public function RegisterIntoDatabase()
    {
        require "../app/core/database.php";

        $bold_title = $_POST['boldtitle'];
        $title = $_POST['title'];
        $subtitle = $_POST['subtitle'];
        $image = $this->new_name;

        $sql = "INSERT INTO images (title_1, title_2, subtitle, image, thumb)
         VALUES ('$bold_title', '$title', '$subtitle', '$image', '$image')";
        $connection->query($sql);
    }
}
 

Проблема в том, что функция RandomStringGenerator() запускается несколько раз и генерирует два разных имени файла изображения, что приводит к сбою функции RunCrop (), поскольку она не может найти это конкретное имя файла в пути. Как я могу это исправить?

Ответ №1:

Включение php GD в настройках XAMPP решило мою проблему.