限制从SQL表检索到的图像的大小

|| 我正在制作旋转式横幅系统,但是存在图像尺寸显示不一致的问题。我将图像存储在SQL表中。我知道在SQL表中存储图像的坏习惯,但是我只存储了几个文件。我需要将图片显示尺寸固定为150像素x 150像素。我该如何使用php?提前致谢 这是我到目前为止的代码:
<?php
require (\"connect.php\");

$id = mysql_real_escape_string($_REQUEST[\'id\']);
$query = mysql_query(\"SELECT * FROM banner WHERE id= $id \");
$row = mysql_fetch_array($query);
$content = $row[\'image\'];
header(\'Content-type: image/jpg\');
echo $content;
?>

<html>
    <head>
        <style type=\"text/css\">
            a
            {
                text-decoration:none;
            }
        </style>
    </head>
    <body>

    <?php
require (\"connect.php\");

$query = mysql_query(\"SELECT * FROM banner\");
$number = mysql_num_rows($query);
$result = mysql_query(\"SELECT * FROM banner ORDER BY RAND() LIMIT 1 \");

while ($row = mysql_fetch_assoc($result))
{
    echo \'<a href = \' . $row[url] . \'> <img src= \"get.php?id= \' . $row[id] . \' \"/> </a>\';
    echo \"<br />\";
    echo \'<a href = \' . $row[url] . \'> \' . $row[description] . \' </a>\';
}

echo mysql_error();
?>

    </body>
</html>
    
已邀请:
好吧,如果您可以控制图像,并且它们只需要为150px x 150px,我建议您只需手动更改它们的大小,然后将其上传回数据库。 现在,您必须执行的操作方式意味着您将在每次加载页面时即时调整图像大小,这很糟糕。要使它起作用,您要做的就是将width和height参数传递给img标签,如下所示
<img src=\"yourimage\" width=\"150\" height=\"150\" />
    
您可以使用外部库调用gd缩放图像。 尽管我从未使用过它,但是有一个叫做imagecreatefromstring()的东西。 (我用了其余的代码,顺便说一句。。。我永远不会在数据库中存储图像)。
$size = 150;
// This is a reference to your MySQL row.
$img = imagecreatefromstring($row[\'image_data\']);
$width = imagesx($img);
$height = imagesy($img);

$aspect = $height/$width;

// This is a simple width check limiter.  There are dozens of ways to treat this,
// so code away until you get what you want.  Personally, I have a 3K line class to handle
// all of the different ways I may want to change this scaling around.
if ($width < $size) 
{
   $w = $width;
   $h = $height;
}
else 
{
   $w = $size;
   $h = floor($w*aspect);
}

$buffer = imagecreatetruecolor($w,$h);

// There are some more advanced ways of doing this if you need an alpha channel.
imagecopyresized($buffer,$img,0,0,0,0,$w,$h,$width,$height);

// File is now copied and ready to go.  You should save your file with a unique, but 
// reconstructable name.  For instance, if your parameters to get here was 
// \'image.php?image_id=25\', I\'d actually md5(\'image.php?image_id=25\') and cache it.  In the
// future, you could check your cache to see if the image was there before you even make your
// DB call, which would speed things up greatly.

// I show an example in the code.

//    $filename = \'/var/www/public/\'.md5(\'image.php?\'.$_SERVER[\'query_string\'].\'_\'.$size);
$filename = \'test.jpg\';
imagejpeg($buffer, $filename, 85 );

header(\'Content-Type: image/jpeg\');
echo file_get_contents($filename);

imagedestroy($buffer);
imagedestroy($img);
    

要回复问题请先登录注册