为特定文件夹中的图像创建缩略图

2024-09-30 22:15:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用Wand(imagemagick)for python创建图像缩略图(250x250px)。在

我希望结果类似于PHP的imagecopyresampled()**函数,如果可能的话,没有质量损失。在

我的目录结构如下:

> 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.

现在我想实现的是为每个图像名.jpg图像,替换旧的imagename_拇指.jpg新图片。在

请注意:在产品文件夹中也有一些图片,但我不想为这些图片创建缩略图,所以在遍历文件时是否可以避免这个文件夹?在

原因:我们最近决定重新设计一款使用更大缩略图的在线应用程序。几乎不可能用手替换所有现有的小缩略图。在


**解释imagecopyresampled()函数(裁剪、重采样),以便更好地理解我想要实现的拇指类型:

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.


Tags: andoftheimagesrcnumberfolderlevel
1条回答
网友
1楼 · 发布于 2024-09-30 22:15:06

从我的答案重新发布到same question on superuser。 (在你决定使用魔杖之前。因此,您应该交换子进程调用以转换为相应的Wand调用。)

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)

相关问题 更多 >