【发布时间】: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,我已经测试过了。它们都按预期生成男性和女性化身。