【发布时间】:2010-06-11 21:09:42
【问题描述】:
我一直在使用这个小 sn-p 来选择随机图像。但是我想将其更改为仅选择特定尺寸的图像。我在检查图像大小时遇到了麻烦。如果我使用 get_image_dimensions() 我需要使用条件语句,这要求我允许异常。所以,我想我需要一些关于仅限制图像尺寸的指示。谢谢。
import os
import random
import posixpath
from django import template
from django.conf import settings
register = template.Library()
def is_image_file(filename):
"""Does `filename` appear to be an image file?"""
img_types = [".jpg", ".jpeg", ".png", ".gif"]
ext = os.path.splitext(filename)[1]
return ext in img_types
@register.simple_tag
def random_image(path):
"""
Select a random image file from the provided directory
and return its href. `path` should be relative to MEDIA_ROOT.
Usage: <img src='{% random_image "images/whatever/" %}'>
"""
fullpath = os.path.join(settings.MEDIA_ROOT, path)
filenames = [f for f in os.listdir(fullpath) if is_image_file(f)]
pick = random.choice(filenames)
return posixpath.join(settings.MEDIA_URL, path, pick)
【问题讨论】:
标签: python django image size limit