Django 使用 ImageKit 进行的ImageField 图像处理

 

有图像的话,肯定不知保存,需要改变图像的像素,大小等,这就需要第三方的lib

pip install -U django-imagekit
pip install -U Pillow

 

settings.py 里面,追加imagekit   ,MEDIA_URL,MEDIA_ROOT

 

model.py

from django.db import models
from imagekit.models import ImageSpecField, ProcessedImageField
from imagekit.processors import ResizeToFill


class Image(models.Model):

    origin = models.ImageField(upload_to="photos/%y/%m/%d/")

    big = ImageSpecField(source="origin",
                         processors=[ResizeToFill(1280, 1024)],
                         format='JPEG'
                         )

    thumbnail = ImageSpecField(source='origin',
                            processors=[ResizeToFill(250,250)],
                            format="JPEG",
                            options={'quality': 60}
                            )

    middle = ImageSpecField(source='origin',
                        processors=[ResizeToFill(600, 400)],
                        format="JPEG",
                        options={'quality': 75}
                        )

    small = ImageSpecField(source='origin',
                            processors=[ResizeToFill(75,75)],
                            format="JPEG",
                            options={'quality': 50}
                            )

template.html

<ul class="list-unstyled image-list">
    {% for image in image_list %}
    <li>
        <a href="{% url 'image_detail' image.id %}">
            <img src="{{ image.thumbnail.url }}" width="250">
        </a>
    </li>
    {% endfor %}
</ul>

 

 view.py

views.py

from django.views.generic import ListView

from images.models import Image


class ImageListView(ListView):
    model = Image
    context_object_name = 'image_list'

 

 

forms.py

from django.forms import ModelForm
from images.models import Image

class UploadFileForm(ModelForm):
    class Meta:
        model = Image
        fields = ["origin", ]

 

upload.html

{% extends 'base.html' %}

{% block content %}

<form method="POST" action="{% url 'image_upload' %}" enctype="multipart/form-data">
  {% csrf_token %}
  {% load crispy_form_tags %}
  {{ form|crispy }}

  <button class="btn btn-primary" type="submit">アップロード</button>
</form>

{% endblock %}

 

posted @ 2023-07-09 17:58  花生与酒  阅读(91)  评论(0编辑  收藏  举报