Ресайз изображений - как решить?

mleit

Новичок
Товарищи, помогите советом, пожалуйста.
Дано: CMS PHPMars (типа инстаграм ;))
При публикации изображений не могу сделать, чтобы высота сохранялась в пропорциях относительно ширины.
По идее за это уже в момент публикации отвечают следующие строки файла photo.php:

Код:
    if(empty($_SESSION['error'])) {
        /* Generate new name  */
        $photo_new_name = md5(time().rand()) . '.' . $photo_file_extension;

        /* Make a thumbnail and upload the original */
        resize($photo_file_temp, ROOT . PHOTOS_ROUTE . $photo_new_name, '900', '600');
        move_uploaded_file($photo_new_name, ROOT . PHOTOS_THUMBS_ROUTE . $photo_new_name);


        /* Execute query */
        $database->query("INSERT INTO `photos` (`user_id`, `name`, `content`, `timestamp`) VALUES ({$account_user_id}, '{$photo_new_name}', '{$content}', UNIX_TIMESTAMP())");
    }

    redirect();
}
Здесь проставлено 900х600, но изображения будут самых разных форматов... как справиться с этим делом?

Полный код файла (вдруг я что-то не так понял...):

Код:
<?php
include '../../core/init.php';
Security::csrf_page_protection_check('dynamic');
User::check_permission(0);

if($_POST['type'] == 'post') {
    /* Define some variables */
    $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
    $photo = (empty($_FILES['photo']['name']) == false) ? true : false;
    $content = filter_var($_POST['content'], FILTER_SANITIZE_STRING);

    /* Error checks */
    if(strlen($content) > 256) {
        $_SESSION['info'][] = $language->home->info_message->content_length;
    }
    if(!$photo) {
        $_SESSION['error'][] = $language->home->error_message->invalid_photo;
    }

    if($photo) {
        $photo_file_name        = $_FILES['photo']['name'];
        $photo_file_extension    = explode('.', $photo_file_name);
        $photo_file_extension    = strtolower(end($photo_file_extension));
        $photo_file_temp        = $_FILES['photo']['tmp_name'];
        $photo_file_size        = $_FILES['photo']['size'];

        if($_FILES['photo']['error']) {
            $_SESSION['error'][] = $language->profile->error_message->invalid_photo;
            redirect();
        }
        list($photo_width, $photo_height)    = getimagesize($photo_file_temp);

        if(!is_writeable(ROOT . PHOTOS_ROUTE) || !is_writeable(ROOT . PHOTOS_THUMBS_ROUTE)) {
            $_SESSION['error'][] = $account->type > 0 ? $language->home->error_message->not_writeable : $language->global->error_message->system_issues;
        }
        if(in_array($photo_file_extension, $allowed_extensions) !== true) {
            $_SESSION['error'][] = $language->global->error_message->invalid_file_type;
        }
        if($photo_width < 150 || $photo_height < 150) {
            $_SESSION['error'][] = $language->profile->error_message->small_photo;
        }
        if($photo_file_size > $settings->photos_max_size) {
            $_SESSION['error'][] = sprintf($language->global->error_message->invalid_image_size, formatBytes($settings->photos_max_size));
        }

    }




// ИЗМЕНЕНИЕ РАЗМЕРА ИЗОБРАЖЕНИЯ "НАЛЕТУ" ПРИ ЗАГРУЗКЕ

    if(empty($_SESSION['error'])) {
        /* Generate new name  */
        $photo_new_name = md5(time().rand()) . '.' . $photo_file_extension;

        /* Make a thumbnail and upload the original */
        resize($photo_file_temp, ROOT . PHOTOS_ROUTE . $photo_new_name, '900', '600');
        move_uploaded_file($photo_new_name, ROOT . PHOTOS_THUMBS_ROUTE . $photo_new_name);


        /* Execute query */
        $database->query("INSERT INTO `photos` (`user_id`, `name`, `content`, `timestamp`) VALUES ({$account_user_id}, '{$photo_new_name}', '{$content}', UNIX_TIMESTAMP())");
    }

    redirect();
}


elseif($_POST['type'] == 'repost') {

    /* Get the photo id and some details */
    $photo_id = (int) $_POST['photo_id'];
    $photo = Database::get('*', 'photos', ['photo_id' => $photo_id]);

    /* Get the extension of the photo */
    $explode = explode('.', $photo->name);
    $photo_file_extension = end($explode);

    /* Generate a new name */
    $photo_new_name = md5(time().rand()) . '.' . $photo_file_extension;

    /* Duplicate the image */
    copy(ROOT.PHOTOS_ROUTE.$photo->name, ROOT.PHOTOS_ROUTE.$photo_new_name);
    copy(ROOT.PHOTOS_THUMBS_ROUTE.$photo->name, ROOT.PHOTOS_THUMBS_ROUTE.$photo_new_name);

    // TODO: ERROR CHECKING.

    Database::insert('photos', [
        'user_id' => $account_user_id,
        'name' => $photo_new_name,
        'content' => sprintf($language->photo->repost->content, '@' . Database::simple_get('username', 'users', ['user_id' => $photo->user_id])),
        'timestamp' => time()
    ]);

    Notifications::insert($account_user_id, $photo->user_id, 'REPOST', $photo->photo_id);

    Response::json($language->photo->success_message->repost, 'success');
}


elseif($_POST['type'] == 'delete') {

    /* Get the photo id */
    $photo_id = (int) $_POST['photo_id'];

    /* Check if the photo is bound to the specific account */
    $photo_user_id = Database::simple_get('user_id', 'photos', ['photo_id' => $photo_id]);

    /* Remove the photo */
    if($photo_user_id == $account_user_id) {

        Photos::delete_photo($photo_id);

        echo 'deleted';
    }

    else {
        echo 'not-deleted';
    }

}

elseif($_POST['type'] == 'like') {

    /* Get the photo id */
    $target_id = (int) $_POST['photo_id'];

    /* Check if the like is set or not already */
    $like_status = Database::simple_get('id', 'associations', ['first_id' => $account_user_id, 'second_id' => $target_id, 'type' => 'PHOTO', 'sub_type' => 'LIKE']);

    /* Remove the like from the database */
    if($like_status) {
        $database->query("DELETE FROM `associations` WHERE `type` = 'PHOTO' AND `sub_type` = 'LIKE' AND `first_id` = {$account_user_id} AND `second_id` = {$target_id}");
        echo 'deleted';
    }

    /* Insert the like in the database */
    else {
        /* Get the user_id of the photo owner */
        $photo_user_id = Database::simple_get('user_id', 'photos', ['photo_id' => $target_id]);

        $database->query("INSERT INTO `associations` (`type`, `sub_type`, `first_id`, `second_id`) VALUES ('PHOTO', 'LIKE', {$account_user_id}, {$target_id})");

        if($account_user_id != $photo_user_id) {
            Notifications::insert($account_user_id, $photo_user_id, 'PHOTO_LIKE', $target_id);
        }

        echo 'inserted';
    }

}

?>
 

mleit

Новичок
Очень исчерпывающе, но арифметика с первого класса, а в пятом - уже математика переходящая в алгебру. И можно б было подсказать, а не понтами себе карму зарабатывать.
 

AnrDaemon

Продвинутый новичок
Вам подсказали. А "на слабо" писать за вас рабочий код никто не будет.
 
Сверху