douyi5822 2012-02-26 19:23
浏览 34
已采纳

扫描目录并从现有图像创建缩略图

What I'm trying to accomplish with this code is, first it scans a directory after images, then it takes one image and create a thumbnail out of it if its bigger than 170x170. The problem I'm having is when I try to load the new file it doesn't work quite as expected.

<?php
foreach (glob('img/*.png') as $f) {
    $list[filemtime($f) . '-' . $f] = $f;
}   

$keys = array_keys($list);      
sort($keys);

$picOne = $list[array_pop($keys)];
$picTwo = $list[array_pop($keys)];
$picThree = $list[array_pop($keys)];
$picFour = $list[array_pop($keys)];

list($width, $height) = getimagesize($picOne);
if ($width > 170 && $height > 170) {
    $thumb = imagecreatetruecolor(170, 170);
    $source = imagecreatefrompng($picOne);
    imagecopyresized($thumb, $source, 0, 0, 0, 0, 170, 170, $width, $height);
    $path = $picOne."_170x170.png";
    imagepng($thumb, $path);
}

echo '<a href="'.$picOne.'" /><img width=170 height=170 src="'.$picOne.'" /></a>&nbsp;&nbsp;'; 
echo '<a href="'.$picTwo.'" /><img width=170 height=170 src="'.$picTwo.'" /></a>&nbsp;&nbsp;'; 
echo '<a href="'.$picThree.'" /><img width=170 height=170 src="'.$picThree.'" /></a>&nbsp;&nbsp;';  
echo '<a href="'.$picFour.'" /><img width=170 height=170 src="'.$picFour.'" /></a>';   

?>

This code should make a new file, right?

$path = $picOne."_170x170.png";
imagepng($thumb, $path)

That part works fine sure but $picOne gets _170x170.png added to it and I don't understand why. What I think I've done is just to create a new file with the $picOne name + _170x170.png but instead $picOne gets it as well.

Can anyone help me fix this code or explain what I need to do to get it to work?

Here's what I'm trying to do basically: 1. Scan a directory. 2. Take an image and create a thumbnail from it. 3. Output the thumbnail.

  • 写回答

1条回答 默认 最新

  • dqm7854 2012-02-26 19:33
    关注

    The reason you are having issue is that you are not creating new file but overwriting existing file. To create new file every time you try using this loop :

        $path =  $picOne."_170x170.png";
    
        $x = 0 ;
        while (file_exists($path))
        {
            $path = $picOne ."-" . $x . ."_170x170.png"; 
            $x++;
        }
    

    This would always give you a new file name all the time and you can put it in a simple function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?