Panny Monium
Panny Monium

Reputation: 301

PHP batch convert all images in a folder to jpg using Image Magick

I have uploaded a number of images with different formats to a folder on my server. Using ImageMagick I want to convert them and replace them to JPG.

This is my code:

<?php

try
{
        /*** the image file ***/
        $image = 'temp_images/*.*';

        /*** a new imagick object ***/
        $im = new Imagick();

        /*** ping the image ***/
        $im->pingImage($image);

        /*** read the image into the object ***/
        $im->readImage( $image );

        /**** convert to png ***/
        $im->setImageFormat( "jpg" );

        /*** write image to disk ***/
        $im->writeImage( 'temp_images/input/*.jpg' );

        echo 'Image Converted';
}
catch(Exception $e)
{
        echo $e->getMessage();
}

?>

When I specify a particular image it converts it, when I replace say abc.gif to *.* I get the following error.

'unable to open image temp_images/input/*.*: No such file or directory @ error/blob.c/OpenBlob/2638'

In the documentation I read that I can use mogrify but I do not know who to insert comand line into PHP.

Upvotes: 0

Views: 1508

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 207345

You don't really need PHP for that, you can do it in the shell directly:

#!/bin/bash
shopt -s nullglob nocaseglob # Ignore case and errors
for i in *.png *.tif *.bmp   # Do all images except JPEGs
do
   newname=${i%.*}.jpg       # Strip file extension
   convert "$i" "$newname"   # Convert to JPEG
done

Or, if you really want to do it within PHP, you can use system() to execute the script above.

Upvotes: 0

ceejayoz
ceejayoz

Reputation: 179994

You can't specify a filename with wildcards like that.

You can use http://php.net/glob or the directory functions to fetch a list of files matching your requirements, and then step through them using a foreach loop.

Upvotes: 1

Related Questions