def square_fit_media(max_length, filename): if not is_image(filename): return full_media(filename) ok_filepath = generate_file_path(filename) filepath = os.path.join(settings.IMAGES_FILE_PATH, "square/{}/{}".format(max_length, ok_filepath)) if not os.path.exists(filepath): try: image = Image.open( os.path.join(settings.FULL_IMAGE_FILE_PATH, ok_filepath)) except IOError: return "Not found", 404 image_dir = filepath[:filepath.rfind("/") + 1] if not os.path.exists(image_dir): os.makedirs(image_dir, mode=0o777) image_width = float(image.size[0]) image_height = float(image.size[1]) image_square = int(min(image_width, image_height)) crop_coordinates_x = int(image_width / 2 - image_square / 2) crop_coordinates_y = int(image_height / 2 - image_square / 2) image = image.crop((crop_coordinates_x, crop_coordinates_y, crop_coordinates_x + image_square, crop_coordinates_y + image_square)) image.thumbnail((max_length, max_length), Image.ANTIALIAS) image.save(filepath, quality=settings.IMAGE_QUALITY) return x_accel_response("/images/square/{}/{}".format( max_length, ok_filepath))
def width_fit_media(max_length, filename): if not is_image(filename): return full_media(filename) ok_filepath = generate_file_path(filename) filepath = os.path.join(settings.IMAGES_FILE_PATH, "width/{}/{}".format(max_length, ok_filepath)) if not os.path.exists(filepath): try: image = Image.open( os.path.join(settings.FULL_IMAGE_FILE_PATH, ok_filepath)) except IOError: return "Not found", 404 image_dir = filepath[:filepath.rfind("/") + 1] if not os.path.exists(image_dir): os.makedirs(image_dir, mode=0o777) image_width = float(image.size[0]) image_height = float(image.size[1]) new_width = int(max_length) new_height = int(new_width / image_width * image_height) image.thumbnail((new_width, new_height), Image.ANTIALIAS) image.save(filepath, quality=settings.IMAGE_QUALITY) return x_accel_response("/images/width/{}/{}".format( max_length, ok_filepath))
def full_media(filename): if is_image(filename): return x_accel_response("/images/max/{}".format( generate_file_path(filename))) return x_accel_response("/videos/{}".format(generate_file_path(filename)))