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

时间:2011-05-24 07:49:09

标签: php mysql html image

我正在制作一个旋转横幅系统,但是存在图像尺寸显示不一致的问题。我将图像存储在SQL表中。我知道将图像存储在SQL表中的不良做法,但我只存储了一些文件。我需要将图像显示尺寸固定为150像素×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>

2 个答案:

答案 0 :(得分:1)

如果您可以控制图像并且它们只需要150px x 150px,我建议您只需手动更改它们的大小并将它们上传回数据库。

现在你必须这样做的方式意味着你每次加载页面时都会动态调整图像大小。要做到这一点,你所做的就是将宽度和高度参数传递给img标签,如此

<img src="yourimage" width="150" height="150" />

答案 1 :(得分:1)

您可以使用外部库调用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);