Reputation: 77
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> ';
echo '<a href="'.$picTwo.'" /><img width=170 height=170 src="'.$picTwo.'" /></a> ';
echo '<a href="'.$picThree.'" /><img width=170 height=170 src="'.$picThree.'" /></a> ';
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.
Upvotes: 1
Views: 367
Reputation: 95161
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.
Upvotes: 1