[Answered ]-Python pil image to django imagefield convert

1👍

from django.core.files.base import ContentFile
from PIL import ImageOps, Image as pil_image
import os.path
import json


def ajax_upload(request):
    if request.method == 'POST':
        newfile = Image()
        newfile.user = request.user
        file_content = ContentFile(request.raw_post_data)
        file_name = request.GET.get('file')

        newfile.image.save(file_name, file_content)
        newfile.thumbnail.save(file_name, file_content)

        #opening and resizing the thumbnail
        path = os.path.join(settings.MEDIA_ROOT, newfile.thumbnail.url)
        thumb_file = pil_image.open(path)

        if thumb_file.mode not in ("L", "RGB"):
            thumb_file = thumb_file.convert("RGB")

        thumb_image_fit = ImageOps.fit(thumb_file, (100, 100), pil_image.ANTIALIAS)
        thumb_image_fit.save(path)

        #===============================================================

        results = {
                    'image':
                        {
                            'url': newfile.image.path,
                            'width': newfile.image.width,
                            'height': newfile.image.height
                        },
                    'thumbnal':
                         {
                            'url': newfile.thumbnail.path,
                            'width': newfile.thumbnail.width,
                            'height': newfile.thumbnail.height
                         }
                    }
        return HttpResponse(json.dumps(results))
    raise Http404

1👍

You can save the file and assign its path (relative to MEDIA_ROOT) to destination field manually.

thumb_path = 'uploads/1_small.jpg'
thumb_image_fit.save(os.path.join(MEDIA_ROOT, thumb_path), 'JPEG', quality=75)
newfile.thumbnail = thumb_path

Surely you’ll need to do all Django’s stuff manually – check if the file exists, modify name if it does, and so on.

👤ilvar

Leave a comment