php - 如何使用 PHP 从 mySQL 数据库获取图像并调整其尺寸?

标签 php mysql image resize

更新:对于其他对此有疑问的人,请查看 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/

相关文章:

php - 脚本@php artisan package :discover handling the post-autoload-dump event returned with error code 255

php - HTTPS 和加密数据库在共享主机中真的安全吗?

PHP如何在这种情况下优化写入文件

php - define() 中的翻译消息

xml - 如何通过 XSL 从现有 XML 文件中的字符串正确调用图像?

android - 如何在 Android 应用程序中将图片发布到 Google Plus

android - JPEG 方向功能如何工作?

php - 一个巨大的 XML 文件是否包含长 SQL 语句?

javascript - 如何在href中添加半链接?

mysql - Groovy SQL - 将一个查询的结果存储在一个列表中,以便在另一个查询中迭代