【问题标题】:Sorting images by height/orientation按高度/方向对图像进行排序
【发布时间】:2018-05-05 09:10:39
【问题描述】:

我用网格视图制作了图片库,但我不喜欢行的样子 - 垂直照片会破坏一切。由于我不想手动更改图像顺序,因此我正在寻找一种按图像高度或仅图像方向自动对它们进行排序的方法,因此垂直照片会排在一行的底部。

这就是我在 Django 中的模型的样子:

class Photo(models.Model):
    title = models.CharField(max_length=150)
    image = models.ImageField()
    description = models.TextField(blank=True)
    category = models.IntegerField(choices=CATEGORIES)
    published = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.title

这是我的 grid_view:

def photos_grid(request):
    global cat_list
    photos = Photo.objects.order_by('published')
    output = {'photos': photos, 'categories': cat_list,}
    return render(request, 'photos/photos_grid.html', output)

我尝试了 (how to find height and width of image for FileField Django) 获取图像尺寸的方法,但我得到了

ValueError: invalid literal for int() with base 10: 'height'

我尝试将它放在我的代码中的每一种方式。其他想法(通过在views.py 中手动获取尺寸)可行,但我无法将其与列表中的照片放在一起,以便对其进行排序。

【问题讨论】:

  • 您是否考虑过使用 Sorl 只是先将它们全部裁剪并摆脱无用的查询?
  • 是的,但是有些照片在裁剪后看起来不正常 - 我前段时间在 Facebook 上遇到过这个问题,并且讨厌缩略图中看不到图片的重要部分。
  • 然后将几何图形添加到模型中,即 offset_x 和 offset_y。并分别裁剪。像这样:dpaste.com/2KWFSHE

标签: python django django-views


【解决方案1】:

您必须在模型中包含高度和宽度字段,例如:

class Photo(models.Model):
    image = models.ImageField(height_field='image_height', width_field='image_width')
    image_height = models.IntegerField()
    image_width = models.IntegerField()
    ...

迁移数据库后,您可以编写以下代码:

Photo.objects.all().order_by('image_height')

编辑:如果需要访问方向,再添加一个字段,如:

class Photo(models.Model):
    ...
    aspect_ratio = models.FloatField(blank=True, null=True)

然后,覆盖您的保存方法以使用高度和宽度填充此字段,即:

class Photo(models.Model):
    ...
    def save(self, **kwargs):
        self.aspect_ratio = float(self.image_height) / float(self.image_width)
        super(Photo, self).save(kwargs)

然后您可以按新字段排序,例如:

Photo.objects.all().order_by('aspect_ratio')

【讨论】:

    猜你喜欢
    • 2020-05-07
    • 2021-10-14
    • 2015-02-14
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 2013-10-14
    • 1970-01-01
    相关资源
    最近更新 更多