我有一个脚本,可以创建一个图像并调用imagepng将其输出到浏览器.相反,我想将它保存到MySQL数据库(作为blob).我知道如何将文件读入准备好的语句中
while ($data = fread($fp, 1024)) {
$size += strlen($data);
$stmt->send_long_data(0, $data);
}
Run Code Online (Sandbox Code Playgroud)
问题是我不想imagepng写文件只是因为我可以把它读回数据库.
有一个简单的方法吗?
更新: 这是我尝试使用输出缓冲的方式:
ob_start();
imagepng($dst_r,null);
$img = ob_get_clean();
$db = Database::getInstance(); // Singleton on MySQLi
$s = $db->prepare("UPDATE " . $db->getTableName("Users") . " SET `Picture` = ? WHERE `UserID` = ?" );
$s->bind_param('bi', $img, $_POST['UserID']);
$s->send_long_data(0, $img);
$s->execute();
Run Code Online (Sandbox Code Playgroud)
数据库未更新且没有错误.
hal*_*ush 10
从我刚刚在php.net中读到的内容,您可以使用ob_start(),ob_get_contents和ob_end_clean()的混合来实现.
混合,我的意思是:
ob_start();
imagepng($image);
$imageContent = ob_get_contents();
ob_end_clean();
Run Code Online (Sandbox Code Playgroud)
如果我是你,我会把它保存在一个临时文件中,但按你的意愿:)
编辑:我认为您的数据库管理也存在问题.这可能有用
//include here the thing to get $imageContent
$db = Database::getInstance(); // Singleton on MySQLi
$s = $db->prepare("UPDATE " . $db->getTableName("Users") . " SET `Picture` = ? WHERE `UserID` = ?" );
$null = NULL;
$s->bind_param('bi', $null, $_POST['UserID']);
$byteToSend = 1024;//this should equals the max_allowed_packet variable in your mysql config (usually in my.cnf config file)
$i=0;
while ($contentToSend = substr($imageContent, $i, $byteToSend)) {
$s->send_long_data(0, $contentToSend);
$i+=$byteToSend;
}
Run Code Online (Sandbox Code Playgroud)