How to resize thousands of images with PHP script

Questions and postings pertaining to the usage of ImageMagick regardless of the interface. This includes the command-line utilities, as well as the C and C++ APIs. Usage questions are like "How do I use ImageMagick to create drop shadows?".
Post Reply
JayCally
Posts: 2
Joined: 2015-07-23T08:37:15-07:00
Authentication code: 1151

How to resize thousands of images with PHP script

Post by JayCally »

So I'm new to ImageMagick and need to resize thousands of photos on a Wordpress site. Contributors have been posting 5000x5000px images for the past 2 years on this site and we ran out of room. There are way to many images for any WordPress plugin to process and I read that ImageMagick can help.

We can't use command line with our host and they suggested to run a PHP script as they already have ImageMagick installed. I've searched and can't find a good example.

I need to search through the WordPress image folder for all files (lets say) bigger than 1024x1024 and resize them to 1024x1024.

Does anyone have a PHP script that they could share?

Thanks.
Bonzo
Posts: 2971
Joined: 2006-05-20T08:08:19-07:00
Location: Cambridge, England

Re: How to resize thousands of images with PHP script

Post by Bonzo »

The method I would use is use glob() to select all the images starting with for example "a" and the use a foreach loop to modify those then move onto 'b" etc. The reason for this is php will time out after a while.
Alternately you could get all the image names into one array and work on a known number at a time to prevent php timing out.

Also alter your upload code ASAP to resize the images on upload to stop this from happening again!
JayCally
Posts: 2
Joined: 2015-07-23T08:37:15-07:00
Authentication code: 1151

Re: How to resize thousands of images with PHP script

Post by JayCally »

Thanks @Bonzo

I've installed Imsanity on that site to size all those large files down when uploaded through WordPress.

I just gotta come up with a PHP script to size down all those old files.
User avatar
fmw42
Posts: 25562
Joined: 2007-07-02T17:14:51-07:00
Authentication code: 1152
Location: Sunnyvale, California, USA

Re: How to resize thousands of images with PHP script

Post by fmw42 »

To resize a folder of images, use mogrify. See http://www.imagemagick.org/Usage/basics/#mogrify. Save to a new directory so you do not overwrite your originals using the -path option

Are all your images the same format? If not, do you want to change to a common format such as JPG or PNG

Suppose your images are in directory test1 and no other non-image files are there. First create a new directory test2. Then in PHP exec(), put the command

Code: Select all

mogrify -path path2/test2 -format JPG -resize 1024x1024\> *
where path2 is the full path to folder test2.

That will resize any image larger than 1024x1024 into the same name with .JPG as suffix and put it into test2.
Post Reply