class ImageSizeValidator(object): def __init__(self, min_width=None, min_height=None, max_width=None, max_height=None, min_ratio=None, max_ratio=None): self.min_width = min_width self.min_height = min_height self.max_width = max_width self.max_height = max_height self.min_ratio = min_ratio self.max_ratio = max_ratio def __call__(self, value): w, h = Image.open(value).size ratio = float(w)/float(h) errors = [] error_message_size = "%s is {size} pixel {type}. It's supposed to be {comparison} than {limit}px." % value.name error_message_ratio = "%s's width/height ratio is {ratio}. It's supposed to be {comparison} than {limit}" % value.name if self.min_width and w < self.min_width: errors.append(error_message_size.format( size=w, type="wide", comparison="greater", limit=self.min_width) ) if self.min_height and h < self.min_height: errors.append(error_message_size.format( size=h, type="high", comparison="greater", limit=self.min_height) ) if self.max_width and w > self.max_width: errors.append(error_message_size.format( size=w, type="wide", comparison="less", limit=self.max_width) ) if self.max_height and h > self.max_height: errors.append(error_message_size.format( size=h, type="high", comparison="less", limit=self.max_height) ) if self.min_ratio and ratio < self.min_ratio: errors.append(error_message_ratio.format( ratio=ratio, comparison="greater", limit=self.min_ratio) ) if self.max_ratio and ratio > self.max_ratio: errors.append(error_message_ratio.format( ratio=ratio, comparison="less", limit=self.max_ratio) ) if errors: raise ValidationError(errors)