GD库裁剪图像不起作用

GD Library crop image not working

本文关键字:不起作用 图像 裁剪 GD      更新时间:2023-09-26

我正在尝试使用以下脚本裁剪JPG文件:

if (isset($_POST['crop_attempt'])) {
    echo($_POST['path']);
    $source_img = imagecreatefromjpeg($_POST['path']);
    $dest_img = imagecreatetruecolor($_POST['crop_w'], $_POST['crop_h']);
    imagecopy(
        $dest_img,
        $source_img,
        0,
        0,
        $_POST['crop_l'],
        $_POST['crop_t'],
        $_POST['crop_w'],
        $_POST['crop_h']
    );
    imagejpeg($dest_img, $_POST['path']);
    imagedestroy($dest_img);
    imagedestroy($source_img);
}

我通过ajax发送以下Javascript对象中的$_POST变量:

var db_data = {
        left        :   db.offset().left - img_pos.left * ratio,
        top         :   db.offset().top - img_pos.top * ratio,
        width       :   db.width() * ratio,
        height      :   db.height() * ratio,
        crop_attempt:   true,
        path        :   $('._jsImageToCrop').attr('src')
    };

这些值都在通过,我已经从 PHP 脚本中回显了它们,我认为问题与 imagecreatefromjpeg(( 函数有关,任何对 GD 库有更多经验的人都可以提供帮助吗?

谢谢。

考虑 PHP 将从 AJAX 调用中得到什么 - 客户端元素的 src 属性,类似于 /some/subdir/on/your/site/kittens.jpg 。您将该值直接发送到 imagecreatefromjpeg() ,这将在您的服务器上查找不存在的/some/subdir/..........因为它缺少您网站的DOCUMENT_ROOT,这将使实际路径/path/to/your/site/doc/root/some/subdir/....

您永远不应该在这样的文件系统操作中使用外部数据。虽然你只是简单地把它传递给imagecreatefromjpeg((,但它仍然是不安全的,因为你允许用户直接提供完整的路径,这意味着他们可以在你的服务器上加载任何图像,任何地方,他们知道路径。