what is Python Imaging Library and implement in django for rotate image

The Python Imaging Library (PIL) adds image processing capabilities to your Python interpreter. This library supports many file formats, and provides powerful image processing and graphics capabilities.


The current stable version is 1.1.7, released in November 2009. The next release will be 1.2, with “early 2011” as the release target.

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:

#views.py
from PIL import Image as PilImage
from models import Image


def rotate(request):
    #getting instance of the model
    item=Image.objects.get(pk=1)

    #opening image for PIL to access
    im = PilImage.open(image.image)

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

    #saving rotated image instead of original. Overwriting is on. 
    rotated_image.save(item.image.file.name, 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

No comments:

Post a Comment