HTML,PHP和MYSQL图片彼此相邻

时间:2012-05-30 16:32:24

标签: php mysql html image show

因此,假设我的服务器上有许多图像,由用户上传。每张图片在数据库中也有一行包含文件名,类别,文件大小,扩展名和位置等信息。

当我想要显示这些图像时,我使用了mysql_query和while循环。这是有效的,但是图片都有不同的尺寸,它们彼此相邻或相互显示,看起来非常糟糕。

让我们假设我有20张这样的图像,我怎样才能显示5张图像彼此相邻,4行长?

2 个答案:

答案 0 :(得分:2)

假设包含图像数据的数字索引数组:

<div class="row">
<?php
// loop through all my images taking the index and image object
foreach( $images as $idx=>$image ) {

    // If this isn't the 1st image & the modulus of 5 and $idx is 0, make a new row.
    if( $idx > 0 && !(5%$idx) ) {
        </div><div class="row">
    }
    // Print out the image
    echo '<img src="' . $image->filename . '" />';
} ?>
</div>

如果将第一个数除以第二个数,则模数基本上是余数。因此,当我们打印5张图像时,5/5 = 1且没有余数,因此我们创建了一个新行。

我相信这会产生类似的东西:

<div class="row">
<img src="img1.jpg" />
<img src="img2.jpg" />
<img src="img3.jpg" />
<img src="img4.jpg" />
<img src="img5.jpg" />
</div>
<div class="row">
<img src="img6.jpg" />
<img src="img7.jpg" />
<img src="img8.jpg" />
<img src="img9.jpg" />
<img src="img10.jpg" />
</div>

然后可以使用CSS设置样式:

<style type="text/css">
    div.row {
       clear:left;
    }
    div.row img {
       float:left;
    }
</style>

在调整图像大小时,您有两个选项:

  1. 简单选项:在CSS中设置图像宽度(高度将相应缩放)。这不是完美的,如果图像的宽高比(宽度与高度)不同,仍会显得凌乱。
  2. 使用诸如GD或imagick的PHP库(在imagemagick之上的PHP层)调整大小(并在必要时裁剪)。我个人更喜欢GD,因为它与PHP打包在一起,所以它得到了更广泛的支持。也就是说,imagick是更快,更简单的代码,所以这取决于你。 This site可以很好地比较两者之间的图像大小调整。
  3. 编辑:在回答你的问题时,你需要做这样的事情来获得图像数组:

    <?php
    // Build an array of images
    $sql = 'SELECT * FROM images';
    $result = mysql_query( $sql );
    
    while( $obj = mysql_fetch_object( $result ) ) {
        $images[] = $obj;
    }
    ?>
    

答案 1 :(得分:0)

伪代码

$i = 0;
while($row = mysql_fetch_object($result) {
   //displaying image
   ....
   if($i % 4 == 0) {
          echo '<BR>';
   }
   $i++;
}