Jump to content

[SOLVED] scandir() with a for loop Function not working


emma57573

Recommended Posts

Im missing something here

 

Any ideas why this is failing?

Im trying to look at all the images in 'imagetest' optimize them and deposit them into 'imagetest/new'

What am I missing here  ???

<?

$path = "imagetest/";  //path to the folder
$newpath = "imagetest/new/";  //path to the folder

$img_gal = scandir($path);  //scandir() gets all files (and file ext) in a folder and puts them into an array



for($i=0;$i<count($img_gal);$i++){//loop tru the file



$filename=$img_gal[$i];

$img = imagecreatefromjpeg($path.$filename);
header("Content-Type: image/jpeg");
imagejpeg($img, $newpath.$filename, 80);





}

?>


This should help

Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: 'imagetest/.' is not a valid JPEG file in /home/misimeuk/public_html/image_sizes.php on line 16

 

So its not reading the file name properly but I cant work out why. Do you think it should be in a while loop rather than a for loop. Or is it just my crappy code  ???

 

<?

$path = "imagetest/";  //path to the folder
$newpath = "imagetest/new/";  //path to the folder

$files = scandir($path);  //scandir() gets all files (and file ext) in a folder and puts them into an array




foreach ($files as $file) {  //loop tru the file



$img = imagecreatefromjpeg($path.$file);
header("Content-Type: image/jpeg");
imagejpeg($img, $newpath.$file, 80);



}

?>

 

Ive changed the code to the above, this manages to have an effect on one image but comes up with a memory error and the rest are unchanged. There are 6 images in the directory.

 

Any ideas?

You're retrieving every single file/subfolder within imagetest/

This could include files that aren't jpegs, and always includes the . and .. folders..... but you're trying to treat them all as though they were jpeg files.

 

$files = scandir($path);  //scandir() gets all files (and file ext) in a folder and puts them into an array




foreach ($files as $file) {  //loop tru the file
   if (is_file($path.$file)) {  // Ignore folders, symbolic links, etc
      if (strtolower(pathinfo($path.$file,PATHINFO_EXTENSION)) == 'jpg') {  // Only process jpg files
         $img = imagecreatefromjpeg($path.$file);
         imagejpeg($img, $newpath.$file, 80);
         ...
      }
   }
}

 

And get rid of

header("Content-Type: image/jpeg");

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.