nobody
nobody

Reputation: 521

Python PIL fails on Django TemporaryUploadedFile

I have a imaging tool which allows a photographer to upload a file. After uploading I want to check if the uploaded image is indeed a valid JPEG file.

So I wrote the following validate function:

    def validate_JPG(self, image):
    ''' JPEG validation check. '''
    # Since PIL offers a more rubust check to validate if the image
    # is an JPEG this is used instead of checking the file header.
    try:
        img = Image.open(image)
        if img.format != 'JPEG':
            raise JPEGValidationFailed()
        else:
            return True
    except IOError, e:
        self.logger.debug('Error in the JPG validation: {}'.format(e))
        return False

The function is called from the upload view which takes the image:

    uploaded_file = self.request.FILES.get('image_file')

    image_checksum = sha256(uploaded_file.read()).hexdigest()

    if Photos.objects.filter(image_checksum=image_checksum).exists():
        return Response({
            'uploadError': 'Image already exists.'
            }, status=status.HTTP_409_CONFLICT,)
    try:
        self.logger.debug('Parsing: IPTC and EXIF')
        exif, iptc = self.data_parser.process_file(uploaded_file)
    except JPEGValidationFailed, e:
        raise serializers.ValidationError({
            'uploadError': str(e)
            })

    except Exception, e:
        self.logger.error('Error in parsing the IPTC and EXIF data: {}'.format(e))
        raise serializers.ValidationError({
            'uploadError': 'Something has gone wrong.'
            })

This code has been running happily but somehow it is failing now.. The Pillow library is used, Pillow==3.0.0 but also updating to the latest version does not work.

The following error is encountered:

cannot identify image file <TemporaryUploadedFile: YV180707_7856.jpg (image/jpeg)>

Also doing image.seek(0) does not work.

Can someone help me?

Upvotes: 0

Views: 492

Answers (1)

nobody
nobody

Reputation: 521

Okay... so after taking a break and reviewing the code again I noticed a file write with the same uploaded file before it was passed to the view (backup-save):

  file.write(image_file.read())

So the file was already read once. That ment I had to put a image_file.seek(0) before passing it to the view... That was the fix. Hope it helps someone in the end.

Upvotes: 1

Related Questions