【问题标题】:GD Library image generation does not work with mySQL queryGD 库图像生成不适用于 mySQL 查询
【发布时间】:2017-11-14 17:19:53
【问题描述】:

长话短说,我有一个项目需要根据数据库中的数据创建用户头像。头像是使用 imagepng() 和 imagecopy() 函数生成的。

用户的头像可以是男性也可以是女性,并且该偏好保存在 SQL 数据库中的“user_gender”列中,其中“0”=女性,“1”=男性:

Screenshot of table in phpmyadmin

所以我们的想法是我们从数据库中获取数据,将值(0 或 1)分配给一个变量,然后使用该变量生成图像。见以下代码:

<?php

    //Database connection script not included, but works fine

    $id = 1;

        $sqlQuery = "SELECT * FROM table WHERE id = :id";
        $statement = $db->prepare($sqlQuery);
        $statement->execute(array(':id' => $id));

        while($rs = $statement->fetch())
        {
            $gender = $rs['user_gender'];

        }

    if($gender == "0")
    {
        //Allocation of images, file paths
        $bodytype ="images/female/f_body.png";
    }   
    else
    {
        $bodytype ="images/male/f_body.png";
    }

    header('Content-Type: image/png');

    $destination = imagecreatefrompng($bodytype);

    imagealphablending($destination, true);
    imagesavealpha($destination, true);

    imagepng($destination); 
?>

但是,此代码不起作用,因为它会导致浏览器上出现空白的黑色页面。

但是,此代码无需从数据库中提取任何内容,就可以正常工作:

<?php

//taking out the sql query and just creating a $gender variable for testing

$gender = "0";

if($gender === 0)
{
    $bodytype ="images/female/f_body.png";
}   
else
{
    $bodytype ="images/female/f_body.png";
}

header('Content-Type: image/png');

$destination = imagecreatefrompng($bodytype);

imagealphablending($destination, true);
imagesavealpha($destination, true);

imagepng($destination);
?>

这是第二个代码的输出,表明图像生成确实是功能性的,问题很可能是从 sql 到 php 的传递:

Working image generation in browser

如果从数据库中提取变量,我将非常感激知道我做错了什么或提示为什么代码停止工作。

谢谢!

【问题讨论】:

  • 在您的第二个示例中,您在两种情况下都使用女性图像。
  • 仍然没有解决它只是...没有显示在浏览器中的问题。
  • 我明白,但您的测试用例无效。验证 1 和 0 的静态值是否按预期生成女性和男性化身。不要仅仅因为您看不到它的相关性而跳过故障排除步骤。
  • 如果不是绝对必要,您不应该使用 PHP 渲染图像。为什么不使用图像的直接链接?您甚至可以在纯 SQL 中执行此操作,尽管您也可以只使用 PHP 中的 if 语句来链接到适当的图像。 SELECT CONCAT('path/to/folder/', IF(gender = 1, 'male.png', 'female.png'))
  • @Michael,我已经测试过了。它们都按预期生成男性和女性化身。

标签: php mysql sql gd gdlib


【解决方案1】:

我尝试了您的代码并遇到了同样的问题,所以我对其进行了一些挖掘,发现数据库没有返回任何内容,所以我所做的就是在数据库名称和表名前面加上前缀,并且它工作正常。见下面的代码

$gender = '';

$sqlQuery = "SELECT * FROM register.users WHERE id = :id";
$statement = $db->prepare($sqlQuery);
$statement->execute(array('id' => 1));

while($rs = $statement->fetch())
{
    $gender = $rs['gender'];
}

if($gender == 0)
{
    $bodytype ="images/female/f_body.png";
}
else if($gender == 1)
{
    $bodytype ="images/male/m_body.png";
}

$destination = imagecreatefrompng($bodytype);

imagealphablending($destination, true);
imagesavealpha($destination, true);

header('Content-Type: image/png');
imagepng($destination);

试试看,告诉我结果如何。

【讨论】:

    猜你喜欢
    • 2016-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    相关资源
    最近更新 更多