Django: Rotate Image with PIL usage.

Let's assume we have this simple model:

from django.db import models

class Image(models.Model):
    image = models.FileField(upload_to="images/")
Task is to take this simple image, rotate it and save instead of original.
Let's discover this way to do so:
from PIL import Image as PilImage
from models import Image

def rotate(request):
    #getting instance of the model

    #opening image for PIL to access
    im =

    #rotating it by built in PIL command
    rotated_image = im.rotate(270)

    #saving rotated image instead of original. Overwriting is on., overwrite=True)

    return HttpResponse(str(image.image))

This pattern will work in most cases. Instead of rotate you can use any other PIL editing method, as for e.g. flip or sharpen the image... Have fun coding and please leave me a comment if you'll find this info useful. Thanks.


Post a Comment

Popular posts from this blog

Python converting PDF to Image

How to disable/enable an element with jQuery or Javascript

Django: Resetting Passwords (with internal tools)