Django,sorl-thumbnail作物图片头

Asi*_*nox 3 django sorl-thumbnail

伙计们,我想知道sorl-thumbnail是否有从底部到顶部裁剪的任何选项...我有一个垃圾问题,在一些图片中,sorl-thumbnail正在裁剪图片中人物的头部.

谢谢

Chi*_*Tol 5

我不相信这是内置到solr-Thumbnails中的,但是这里是一个插件,我从reddit中抄下来完成你所追求的.它并不完美,但它往往可以完成工作.它不会从底部到顶部进行裁剪,而是使用切片的熵来确定裁剪的最终结果.这是reddit版本的略微改进,因为它处理纵向或横向图像.

import Image, ImageFile, math
#from ImageEnhance import Color
#import os, sys


def image_entropy(im):
    """From Reddit: Calculate the entropy of an image"""
    hist = im.histogram()
    hist_size = sum(hist)
    hist = [float(h) / hist_size for h in hist]
    return -sum([p * math.log(p, 2) for p in hist if p != 0])

def square_image(im, requested_size, opts):
    """From Reddit: if the image is taller than it is wide, square it off. determine
    which pieces to cut off based on the entropy pieces.

    This version is improved as it squares images that are wider than it is tall.
    """
    if 'autosquare' in opts:
        x,y = im.size

        # if the image is taller than it is wide:
        if y > x:
            while y > x:
                #slice 10px at a time until square
                slice_height = min(y - x, 10)

                bottom = im.crop((0, y - slice_height, x, y))
                top = im.crop((0, 0, x, slice_height))

                #remove the slice with the least entropy
                if image_entropy(bottom) < image_entropy(top):
                    im = im.crop((0, 0, x, y - slice_height))
                else:
                    im = im.crop((0, slice_height, x, y))

                x,y = im.size

        # If the image is wider than it is tall
        else:
            while y < x:
                #slice 10px at a time until square
                slice_width = min(x - y, 10)

                left = im.crop((0,0, y, slice_width))
                right = im.crop((0,y - slice_width, x, y))

                #remove the slice with the least entropy
                if image_entropy(left) < image_entropy(right):
                    im = im.crop((0, 0, x - slice_width, y))
                else:
                    im = im.crop((slice_width, 0, x, y))

                x,y = im.size

        im = im.resize(requested_size, resample=Image.ANTIALIAS)

    return im
square_image.valid_options = ('autosquare',) 
Run Code Online (Sandbox Code Playgroud)


Smi*_*ris 5

我刚刚发布了一个新版本的sorl-thumbnail(3.2.5),其边缘智能裁剪的裁剪灵感来自于btol45的答案.

引用文档:

默认情况下,图像在裁剪之前居中.到从边缘裁剪,通过含有一个逗号分隔的字符串xy 百分比偏移量(负值从右侧/底部去).一些例子如下:

  • crop="0,0" 将从左边和上边缘裁剪.

  • crop="-10,-0" 将从右边缘(具有10%偏移)和底边缘裁剪.

  • crop=",0" 将保持x轴的默认行为(水平居中图像)并从顶部边缘裁剪.

图像也可以通过使用"智能裁剪" crop="smart".通过从具有最小熵的边缘移除切片,将图像递增地裁剪为所请求的大小.

  • 请注意,此答案适用于古老版本的sorl-thumbnail,并且不适用于任何更新版本. (2认同)
  • 我添加了一个适用于最近的sorl版本的答案.简而言之,crop ="center top". (2认同)