0

I am using Django Imagekit in models.py:

from imagekit.models import ProcessedImageField    
class AltroUser(models.Model):
        first_name = models.CharField(_('first name'), max_length=30)
        image = ProcessedImageField(upload_to='media/path',
                                    default='user_default.jpg',
                                    processors=[ResizeToFill(640, 640)],
                                    format='JPEG',
                                    options={'quality': 60})

serializers.py:

class UserRegistrationSerializer(Serializer):
    first_name = serializers.CharField()
    image = serializers.ImageField()

I am trying to test the image field. I have tried following methods:

def get_test_image():
    try:
        image = DjangoFile(open(os.path.join(django_settings.MEDIA_ROOT, 'user_default.jpg'),
                                mode='rb'))
        return image
    except (OSError, IOError) as e:
        return None


def get_test_image1():
    file = io.BytesIO()
    image = Image.new('RGBA', size=(100, 100), color=(155, 0, 0))
    image.save(file, 'png')
    file.name = 'test.png'
    file.seek(0)
    return SimpleUploadedFile('abc.jpg', file.read())


def get_test_image2():
    path = os.path.join(django_settings.MEDIA_ROOT, 'user_default.jpg')
    file = File(open(path, 'r+b'))
    return SimpleUploadedFile('abc.jpg', file.read())

I have tried calling the above three methods to set the value of the image key but none of them worked. For get_test_image(), I get a response "The submitted file is empty."

For get_test_image1() and get_test_image2(), I get a response "The submitted file is empty." with an exception before in the data image field '_io.BytesIO' object has no attribute 'encoding'.

I don't understand what am I missing. Please help.

toothie
  • 1,019
  • 4
  • 20
  • 47

2 Answers2

1

Here's an example of what I'm using to generate test image:

from StringIO import StringIO
from PIL import Image
from django.core.files import File

def get_image_file(name='test.png', ext='png', size=(50, 50), color=(256, 0, 0)):
    file_obj = StringIO()
    image = Image.new("RGBA", size=size, color=color)
    image.save(file_obj, ext)
    file_obj.seek(0)
    return File(file_obj, name=name)
mariodev
  • 13,928
  • 3
  • 49
  • 61
0

In Pillow==8.3.1, using StringIO() gave me this error:

TypeError: string argument expected, got 'bytes'.

I used BytesIO() instead and it worked like a charm

from io import BytesIO
def get_image_file(
    self, name="test.png", ext="png", size=(50, 50), color=(256, 0, 0)
):
    file_obj = BytesIO()
    image = Image.new("RGBA", size=size, color=color)
    image.save(file_obj, ext)
    file_obj.seek(0)
    return File(file_obj, name=name)
MD Mushfirat Mohaimin
  • 1,966
  • 3
  • 10
  • 22
Mai Elshiashi
  • 191
  • 2
  • 6