Пример #1
0
    def _save_file(request, uploaded_file):
        filename = get_upload_filename(uploaded_file.name, request.user)

        img_name, img_format = os.path.splitext(filename)
        IMAGE_QUALITY = getattr(settings, "IMAGE_QUALITY", 60)

        if (str(img_format).lower() == "png"):

            img = Image.open(uploaded_file)
            img = img.resize(img.size, Image.ANTIALIAS)
            saved_path = storage.save("{}.jpg".format(img_name), uploaded_file)
            img.save("{}.jpg".format(img_name),
                     quality=IMAGE_QUALITY,
                     optimize=True)

        elif (str(img_format).lower() == "jpg"
              or str(img_format).lower() == "jpeg"):

            img = Image.open(uploaded_file)
            img = img.resize(img.size, Image.ANTIALIAS)
            saved_path = storage.save(filename, uploaded_file)
            img.save(saved_path, quality=IMAGE_QUALITY, optimize=True)

        else:
            saved_path = storage.save(filename, uploaded_file)

        return saved_path
Пример #2
0
def create_thumbnail(file_path):
    thumbnail_filename = utils.get_thumb_filename(file_path)
    thumbnail_format = utils.get_image_format(os.path.splitext(file_path)[1])

    image = storage.open(file_path)
    image = Image.open(image)
    file_format = image.format

    # Convert to RGB if necessary
    # Thanks to Limodou on DjangoSnippets.org
    # http://www.djangosnippets.org/snippets/20/
    if image.mode not in ('L', 'RGB'):
        image = image.convert('RGB')

    # scale and crop to thumbnail
    imagefit = ImageOps.fit(image, THUMBNAIL_SIZE, Image.ANTIALIAS)
    thumbnail_io = BytesIO()
    imagefit.save(thumbnail_io, format=file_format)

    thumbnail = InMemoryUploadedFile(thumbnail_io, None, thumbnail_filename,
                                     thumbnail_format,
                                     len(thumbnail_io.getvalue()), None)
    thumbnail.seek(0)

    return storage.save(thumbnail_filename, thumbnail)