PHP run function for all images from one directory in recursive mode

I have a function

 $result = create_watermark( 'input_file_name' ,'output_file_name');

      

I have a directory called /images

with 500 images in it. All files are named images_(some_unknown_numbers).png

(all png). Now I want to run them through a function in a loop and want to withdraw /markedimage/images_1.png

, images_2.png

, images_3.png

and so on.

I want to run this script in Ubuntu so that we can use the shell too

How can i do this?

+2


a source to share


4 answers


<?php

foreach (glob("*.png") as $filename) {
    create_watermark($filename, '/watermarked_dir/' . $filename);
}

      



+3


a source


I'm not sure if you want to re-index the numbers for the output files. This example should save them:



<?php
$dir = './sourceDir';
$outputDir = './markedimage';

//get files matching pattern. maybe you could use glob() instead
$files = scandir($dir);
$files = preg_grep('~^images_\d+.png$~i', $files);

//process each file
foreach ($files as $file) {
     create_watermark( $dir . '/' . $file, $outputDir . '/' . $file);
}

      

0


a source


Untested, but this should work too:

// Iterate over all filesystem objects in /images
foreach( new DirectoryIterator('/images') as $file ) {
    // check if item is a readable file
    if( $file->isFile() && $file->isReadable() ) {
        // give debug message so we know what the script is doing
        echo "Watermarking $file \n";
        // call your function
        create_watermark(
            // argument 1 is the full path to the image
            $file->getPathname(),
            // argument 2 is the destination folder plus the filename w/out path
            '/markedimage/' . $file->getFilename()
        );
    // tell us if it is not a readable file
    } else {
        echo "Skipped $file \n";
    }
}

      

If there are no png files in the folder, you can use GlobIterator instead of DirectoryIterator, but PHP5.3 will need this.

Cm

0


a source


i used 2nd answer

working

<?php

foreach (glob("*.png") as $filename) {
    create_watermark($filename, '/watermarked_dir/' . $filename);
}
?>

      

this answer worked without any changes: D thankx but I can't vote for it because I am not registered

@ 1 i m failed to get it to work but this i think if put some effort into it it will work

<?php
$dir = './sourceDir';
$outputDir = './markedimage';

//get files matching pattern. maybe you could use glob() instead
$files = scandir($dir);
$files = preg_grep('~^images_\d+.png$~i', $files);

//process each file
foreach ($files as $file) {
     create_watermark( $dir . '/' . $file, $outputDir . '/' . $file);
}

?>

      

thankx to guyz who tried and helped me to highlight, I tried to do it in the last 5 hours but couldn't solve it in five minutes

: D thankxxx

Steve

0


a source







All Articles