嗨,我有一个项目,图像上传并保存在媒体的子文件夹中,并且从未设置图像大小,所以现在图像保存了 4mb,最终总计为 40GB。
如果图像位于单个文件夹中,我知道如何编写脚本,但是有人可以指导我这样做以检查文件夹中的所有图像并调整其大小吗?即使它在一个子文件夹和另一个子文件夹中。
使用 Django 和 python
图片上传功能
def artwork_theme_name(instance, filename):
path, name = get_hashed_upload_to(instance.id, filename)
return 'theme/{}/{}'.format(path, name)
上传模型
class ArtworkForeground(models.Model):
title = models.CharField(_("title"), max_length=128)
description = models.TextField(_("description"))
foreground = models.ImageField(_("foreground image"), upload_to=artwork_theme_name)
在这里,我用缩小尺寸的图像覆盖现有图像。artwork.foreground
是一个file-pointer
,我们将fp传递给了PIL
班。类Image
save()
方法将文件名/路径连接文件名作为第一个参数。此时,.path
属性变得很方便
from PIL import Image
def do_resize(image):
pil_img = Image.open(image)
resize_limit = 100, 150
pil_img.thumbnail(resize_limit, Image.ANTIALIAS)
pil_img.save(image.path)
for artwork in ArtworkForeground.objects.filter(foreground__isnull=False):
do_resize(artwork.foreground)
UPDATE-1
我应该把这个片段放在哪里?
如果你从现在开始设置某种限制或验证,只需在Django Shell中运行此脚本(这仅供一次性使用(
您可以使用os.walk()
函数遍历所有文件和子文件夹。
for (path, dirs, files) in os.walk(path):
for file in files:
filename = os.path.join(path, file)
if filename.endswith('.jpg'):
resize_image(filename)