首页 > 解决方案 > 使用 GD 调整 PHP 图像大小到许多 CPU 时间

问题描述

我有一个关于 PHP GD 的脚本,它具有简单的功能,如何在我的网站上调整实时图像的大小,但是这个过程“吃掉”了我所有的 CPU 时间……我使用 4 核的 VPS,这还不够。

从图像标记中,我<img src="image.php?file=XXX&width=XXX&height=XXX" alt="" />使用图像名称、新宽度和新高度调用 PHP 文件 ()……然后在 PHP 中进行以下操作:

ob_start();

ini_set('max_execution_time', 0);
set_time_limit(0);

error_reporting(E_ALL^E_NOTICE^E_DEPRECATED);
date_default_timezone_set('Europe/Sofia');

header('Content-type: image/jpeg');

    $url = $_GET['file'];

    if(!empty($url) && file_exists($url) && is_file($url) && is_readable($url)){
        $width = $_GET['width'];
        $height = $_GET['height'];

        list($width_orig, $height_orig) = getimagesize($url);

        if(empty($width)) $width = $width_orig/($height_orig/$height);
        if(empty($height)) $height = $height_orig/($width_orig/$width);

        $ratio_orig = $width_orig/$height_orig;

        if($width/$height > $ratio_orig) {
            $width = $height*$ratio_orig;
        } else {
            $height = $width/$ratio_orig;
        }

        $image_p = imagecreatetruecolor($width, $height);
        $image = imagecreatefromjpeg($url);

        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
        imagejpeg($image_p, null, 100);
        imagedestroy($image_p);
        imagedestroy($image);
    }

    ob_end_flush();

我不明白为什么要“吃”来匹配 CPU 时间……我的原始图像尺寸是 1920x2880 像素。如何减少我的 CPU 使用率?有任何想法吗?

标签: phpgdcpu-usageimage-resizing

解决方案


推荐阅读