~widelands-dev/widelands-website/django_staticfiles

« back to all changes in this revision

Viewing changes to wlprofile/fields.py

  • Committer: Holger Rapp
  • Date: 2009-02-21 18:24:02 UTC
  • Revision ID: sirver@kallisto.local-20090221182402-k3tuf5c4gjwslbjf
Main Page contains now the same informations as before

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
from StringIO import StringIO
2
 
from django.db import models
3
 
import logging
4
 
from django.core.files.uploadedfile import SimpleUploadedFile
5
 
 
6
 
 
7
 
class ExtendedImageField(models.ImageField):
8
 
    """Extended ImageField that can resize image before saving it."""
9
 
 
10
 
    def __init__(self, *args, **kwargs):
11
 
        self.width = kwargs.pop('width', None)
12
 
        self.height = kwargs.pop('height', None)
13
 
        super(ExtendedImageField, self).__init__(*args, **kwargs)
14
 
 
15
 
    def save_form_data(self, instance, data):
16
 
        if data is not None and data != self.default:
17
 
            if not data:
18
 
                data = self.default
19
 
                if instance.avatar != self.default:
20
 
                    instance.avatar.delete()
21
 
            else:
22
 
                if hasattr(data, 'read') and self.width and self.height:
23
 
                    content = self.resize_image(
24
 
                        data.read(), width=self.width, height=self.height)
25
 
                    data = SimpleUploadedFile(
26
 
                        instance.user.username + '.png', content, 'image/png')
27
 
            super(ExtendedImageField, self).save_form_data(instance, data)
28
 
 
29
 
    def resize_image(self, rawdata, width, height):
30
 
        """Resize image to fit it into (width, height) box."""
31
 
        from PIL import Image
32
 
 
33
 
        image = Image.open(StringIO(rawdata))
34
 
        try:
35
 
            oldw, oldh = image.size
36
 
 
37
 
            if oldw > width or oldh > height:
38
 
                if oldw >= oldh:
39
 
                    x = int(round((oldw - oldh) / 2.0))
40
 
                    image = image.crop((x, 0, (x + oldh) - 1, oldh - 1))
41
 
                else:
42
 
                    y = int(round((oldh - oldw) / 2.0))
43
 
                    image = image.crop((0, y, oldw - 1, (y + oldw) - 1))
44
 
                image = image.resize((width, height), resample=Image.ANTIALIAS)
45
 
        except Exception, err:
46
 
            logging.error(err)
47
 
            return ''
48
 
 
49
 
        string = StringIO()
50
 
        image.save(string, format='PNG')
51
 
        return string.getvalue()