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.

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

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug