更新:对于其他对此有疑问的人,请查看 http://www.php.net/manual/en/function.imagecreatefromstring.php#31178 上的评论
我将图像存储在数据库表中。它们以原始尺寸上传。 我可以使用 PHP header 将此图像输出到浏览器(例如“getimage.php?imgID=1”),但如果我想在输出到浏览器之前调整图像大小,我就会陷入困境。
我不想写入新文件,我只想从数据库表中获取图像,并调整其大小(最好在同一个 PHP 脚本中)。
这样的东西就完美了:getimage.php?imgID=1&width=75&height=75
谁能告诉我如何用 PHP 做到这一点?
$query= "select * from `tablename`.`photos` where `ImageID` = '".$_GET['imgID']."' LIMIT 1";
$downloadResult = SendQuery("browse",$query); // my own custom php function to connect & send a mysql query
if(is_array($downloadResult)){ //check if a row was returned
foreach($downloadResult as $myfile) {
header("Content-Type: ". $myfile['mime']);
header("Content-Length: ". $myfile['size']);
if($d=="true"){
header('Content-Disposition: inline; filename="'. urlencode($myfile['name']).'"');
}
echo $myfile['data'];
}
最佳答案
您从二进制字符串 ($myfile['data']
) 加载图像数据。您所需要的只是一个能够基于二进制字符串创建图像对象的图像库/扩展。例如GD library可以从字符串加载数据:
$im = imagecreatefromstring($myfile['data']);
然后,您可以采用任何大量示例(包括本网站上已有的大量示例)来根据您的需要调整图像大小。
调整图像大小后,您可以将其输出到浏览器,例如 PNG:
imagepng($im);
imagedestroy($im);
参见imagecreatefromstring
Docs 。如果您使用通过简单界面调整大小的图像库,您可能会发现它很有帮助,例如 Wideimage它也支持从二进制字符串加载。它是基于 GD 的:
WideImage::loadFromString($myfile['data'])
->resize(50, 30)
->output('png');
是的,就是这么简单。请参阅:
关于php - 如何使用 PHP 从 mySQL 数据库获取图像并调整其尺寸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9633772/