Question

I would like to create image thumbnails (250x250px) using Wand (imagemagick) for python.

I want results to be similar to PHP's imagecopyresampled()** function with no quality loss if possible.

My directory structure is the following:

> main folder (level 1) -> only one

>> company folder (level 2 - inside main folder) -> 286 company folders

>>> product folder (level 2 - inside each company folder)
>>> property folders (level 2 - inside each company folder) -> number depending on number of properties that each company owns

>>>> imagename.jpg (level 3 - inside each property folder) -> number depending on number of images.
>>>> imagename_thumb.jpg (level 3 - inside each property folder) -> old, smaller thumbs, one for every original image in folder. These should be deleted/replaced with new ones.

Now what i would like to achieve is to create thumbnail (as described before) for every imagename.jpg image, replacing old imagename_thumb.jpg images with new ones.

PLEASE NOTE: There are also some images inside product folder, but i dont want to create thumbs for these, so is it possible to avoid this folder when looping through files?

REASON: We recently decided to redesign the online app which uses bigger thumbnail images. It is almost impossible to replace all the existing smaller thumbnails by hand.


** Explanation of imagecopyresampled() function (crop, resample) for better understanding what kind of thumbs i want to achieve:

imagecopyresampled() copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity.

In other words, imagecopyresampled() will take a rectangular area from src_image of width src_w and height src_h at position (src_x,src_y) and place it in a rectangular area of dst_image of width dst_w and height dst_h at position (dst_x,dst_y).

If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_image is the same as src_image) but if the regions overlap the results will be unpredictable.

Was it helpful?

Solution

Re-posted from my answer to the same question on superuser. (Before you apparently decided on using Wand. So you should swap the subprocess call to convert for the appropriate Wand calls.)

import os
import subprocess

for root, dirs, files in os.walk('company 3\company 3 property'):
    images = [os.path.join(root, f) for f in files if f.endswith('.jpg') and not '_thumb' in f]
    for f in images:
        outbase = f[:-4] # simply remove '.jpg'
        out = outbase += '_thumb.jpg'
        args = ['convert', f, '-scale', '250x250', out]
        subprocess.call(args)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top