We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Allow use of MPO formatted JPEG images
Just tried loading some JPEG images into a website and was given an error "Not a valid JPEG image please use blah blah".

The images were from my Nikon D3300 which seems to create JPEG files in MPO format. This format is supported by Pillow but Wagtail is blocking them from being uploaded. I disabled the format validation and everything seemed to work fine.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `wagtail/wagtailimages/fields.py`
Content:
```
1 import os
2 
3 from PIL import Image
4 
5 from django.forms.fields import ImageField
6 from django.core.exceptions import ValidationError
7 from django.utils.translation import ugettext_lazy as _
8 from django.template.defaultfilters import filesizeformat
9 from django.conf import settings
10 
11 
12 ALLOWED_EXTENSIONS = ['gif', 'jpg', 'jpeg', 'png']
13 SUPPORTED_FORMATS_TEXT = _("GIF, JPEG, PNG")
14 
15 INVALID_IMAGE_ERROR = _(
16     "Not a supported image format. Supported formats: %s."
17 ) % SUPPORTED_FORMATS_TEXT
18 
19 INVALID_IMAGE_KNOWN_FORMAT_ERROR = _(
20     "Not a valid %s image."
21 )
22 
23 MAX_UPLOAD_SIZE = getattr(settings, 'WAGTAILIMAGES_MAX_UPLOAD_SIZE', 10 * 1024 * 1024)
24 
25 if MAX_UPLOAD_SIZE is not None:
26     MAX_UPLOAD_SIZE_TEXT = filesizeformat(MAX_UPLOAD_SIZE)
27 
28     FILE_TOO_LARGE_ERROR = _(
29         "This file is too big. Maximum filesize %s."
30     ) % (MAX_UPLOAD_SIZE_TEXT, )
31 
32     FILE_TOO_LARGE_KNOWN_SIZE_ERROR = _(
33         "This file is too big (%%s). Maximum filesize %s."
34     ) % (MAX_UPLOAD_SIZE_TEXT, )
35 
36     IMAGE_FIELD_HELP_TEXT = _(
37         "Supported formats: %s. Maximum filesize: %s."
38     ) % (SUPPORTED_FORMATS_TEXT, MAX_UPLOAD_SIZE_TEXT, )
39 else:
40     MAX_UPLOAD_SIZE_TEXT = ""
41     FILE_TOO_LARGE_ERROR = ""
42     FILE_TOO_LARGE_KNOWN_SIZE_ERROR = ""
43 
44     IMAGE_FIELD_HELP_TEXT = _(
45         "Supported formats: %s."
46     ) % (SUPPORTED_FORMATS_TEXT, )
47 
48 
49 class WagtailImageField(ImageField):
50     default_error_messages = {
51         'invalid_image': INVALID_IMAGE_ERROR,
52         'invalid_image_known_format': INVALID_IMAGE_KNOWN_FORMAT_ERROR,
53         'file_too_large': FILE_TOO_LARGE_KNOWN_SIZE_ERROR,
54     }
55 
56     def __init__(self, *args, **kwargs):
57         super(WagtailImageField, self).__init__(*args, **kwargs)
58 
59         self.help_text = IMAGE_FIELD_HELP_TEXT
60 
61     def check_image_file_format(self, f):
62         # Check file extension
63         extension = os.path.splitext(f.name)[1].lower()[1:]
64 
65         if extension not in ALLOWED_EXTENSIONS:
66             raise ValidationError(self.error_messages['invalid_image'], code='invalid_image')
67 
68         if hasattr(f, 'image'):
69             # Django 1.8 annotates the file object with the PIL image
70             image = f.image
71         elif not f.closed:
72             # Open image file
73             file_position = f.tell()
74             f.seek(0)
75 
76             try:
77                 image = Image.open(f)
78             except IOError:
79                 # Uploaded file is not even an image file (or corrupted)
80                 raise ValidationError(self.error_messages['invalid_image_known_format'],
81                     code='invalid_image_known_format')
82 
83             f.seek(file_position)
84         else:
85             # Couldn't get the PIL image, skip checking the internal file format
86             return
87 
88         image_format = extension
89         if extension == 'jpg':
90             image_format = 'jpeg'
91 
92         # Check that the internal format matches the extension
93         # It is possible to upload PSD files if their extension is set to jpg, png or gif. This should catch them out
94         if image.format.upper() != image_format.upper():
95             raise ValidationError(self.error_messages['invalid_image_known_format'] % (
96                 image_format.upper()
97             ), code='invalid_image_known_format')
98 
99     def check_image_file_size(self, f):
100         # Upload size checking can be disabled by setting max upload size to None
101         if MAX_UPLOAD_SIZE is None:
102             return
103 
104         # Check the filesize
105         if f.size > MAX_UPLOAD_SIZE:
106             raise ValidationError(self.error_messages['file_too_large'] % (
107                 filesizeformat(f.size),
108             ), code='file_too_large')
109 
110     def to_python(self, data):
111         f = super(WagtailImageField, self).to_python(data)
112 
113         if f is not None:
114             self.check_image_file_size(f)
115             self.check_image_file_format(f)
116 
117         return f
118
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/wagtail/wagtailimages/fields.py b/wagtail/wagtailimages/fields.py
--- a/wagtail/wagtailimages/fields.py
+++ b/wagtail/wagtailimages/fields.py
@@ -85,15 +85,19 @@
             # Couldn't get the PIL image, skip checking the internal file format
             return
 
-        image_format = extension
-        if extension == 'jpg':
-            image_format = 'jpeg'
+        image_format = extension.upper()
+        if image_format == 'JPG':
+            image_format = 'JPEG'
+
+        internal_image_format = image.format.upper()
+        if internal_image_format == 'MPO':
+            internal_image_format = 'JPEG'
 
         # Check that the internal format matches the extension
         # It is possible to upload PSD files if their extension is set to jpg, png or gif. This should catch them out
-        if image.format.upper() != image_format.upper():
+        if internal_image_format != image_format:
             raise ValidationError(self.error_messages['invalid_image_known_format'] % (
-                image_format.upper()
+                image_format,
             ), code='invalid_image_known_format')
 
     def check_image_file_size(self, f):

{"golden_diff": "diff --git a/wagtail/wagtailimages/fields.py b/wagtail/wagtailimages/fields.py\n--- a/wagtail/wagtailimages/fields.py\n+++ b/wagtail/wagtailimages/fields.py\n@@ -85,15 +85,19 @@\n             # Couldn't get the PIL image, skip checking the internal file format\n             return\n \n-        image_format = extension\n-        if extension == 'jpg':\n-            image_format = 'jpeg'\n+        image_format = extension.upper()\n+        if image_format == 'JPG':\n+            image_format = 'JPEG'\n+\n+        internal_image_format = image.format.upper()\n+        if internal_image_format == 'MPO':\n+            internal_image_format = 'JPEG'\n \n         # Check that the internal format matches the extension\n         # It is possible to upload PSD files if their extension is set to jpg, png or gif. This should catch them out\n-        if image.format.upper() != image_format.upper():\n+        if internal_image_format != image_format:\n             raise ValidationError(self.error_messages['invalid_image_known_format'] % (\n-                image_format.upper()\n+                image_format,\n             ), code='invalid_image_known_format')\n \n     def check_image_file_size(self, f):\n", "issue": "Allow use of MPO formatted JPEG images\nJust tried loading some JPEG images into a website and was given an error \"Not a valid JPEG image please use blah blah\".\n\nThe images were from my Nikon D3300 which seems to create JPEG files in MPO format. This format is supported by Pillow but Wagtail is blocking them from being uploaded. I disabled the format validation and everything seemed to work fine.\n\n", "before_files": [{"content": "import os\n\nfrom PIL import Image\n\nfrom django.forms.fields import ImageField\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.template.defaultfilters import filesizeformat\nfrom django.conf import settings\n\n\nALLOWED_EXTENSIONS = ['gif', 'jpg', 'jpeg', 'png']\nSUPPORTED_FORMATS_TEXT = _(\"GIF, JPEG, PNG\")\n\nINVALID_IMAGE_ERROR = _(\n    \"Not a supported image format. Supported formats: %s.\"\n) % SUPPORTED_FORMATS_TEXT\n\nINVALID_IMAGE_KNOWN_FORMAT_ERROR = _(\n    \"Not a valid %s image.\"\n)\n\nMAX_UPLOAD_SIZE = getattr(settings, 'WAGTAILIMAGES_MAX_UPLOAD_SIZE', 10 * 1024 * 1024)\n\nif MAX_UPLOAD_SIZE is not None:\n    MAX_UPLOAD_SIZE_TEXT = filesizeformat(MAX_UPLOAD_SIZE)\n\n    FILE_TOO_LARGE_ERROR = _(\n        \"This file is too big. Maximum filesize %s.\"\n    ) % (MAX_UPLOAD_SIZE_TEXT, )\n\n    FILE_TOO_LARGE_KNOWN_SIZE_ERROR = _(\n        \"This file is too big (%%s). Maximum filesize %s.\"\n    ) % (MAX_UPLOAD_SIZE_TEXT, )\n\n    IMAGE_FIELD_HELP_TEXT = _(\n        \"Supported formats: %s. Maximum filesize: %s.\"\n    ) % (SUPPORTED_FORMATS_TEXT, MAX_UPLOAD_SIZE_TEXT, )\nelse:\n    MAX_UPLOAD_SIZE_TEXT = \"\"\n    FILE_TOO_LARGE_ERROR = \"\"\n    FILE_TOO_LARGE_KNOWN_SIZE_ERROR = \"\"\n\n    IMAGE_FIELD_HELP_TEXT = _(\n        \"Supported formats: %s.\"\n    ) % (SUPPORTED_FORMATS_TEXT, )\n\n\nclass WagtailImageField(ImageField):\n    default_error_messages = {\n        'invalid_image': INVALID_IMAGE_ERROR,\n        'invalid_image_known_format': INVALID_IMAGE_KNOWN_FORMAT_ERROR,\n        'file_too_large': FILE_TOO_LARGE_KNOWN_SIZE_ERROR,\n    }\n\n    def __init__(self, *args, **kwargs):\n        super(WagtailImageField, self).__init__(*args, **kwargs)\n\n        self.help_text = IMAGE_FIELD_HELP_TEXT\n\n    def check_image_file_format(self, f):\n        # Check file extension\n        extension = os.path.splitext(f.name)[1].lower()[1:]\n\n        if extension not in ALLOWED_EXTENSIONS:\n            raise ValidationError(self.error_messages['invalid_image'], code='invalid_image')\n\n        if hasattr(f, 'image'):\n            # Django 1.8 annotates the file object with the PIL image\n            image = f.image\n        elif not f.closed:\n            # Open image file\n            file_position = f.tell()\n            f.seek(0)\n\n            try:\n                image = Image.open(f)\n            except IOError:\n                # Uploaded file is not even an image file (or corrupted)\n                raise ValidationError(self.error_messages['invalid_image_known_format'],\n                    code='invalid_image_known_format')\n\n            f.seek(file_position)\n        else:\n            # Couldn't get the PIL image, skip checking the internal file format\n            return\n\n        image_format = extension\n        if extension == 'jpg':\n            image_format = 'jpeg'\n\n        # Check that the internal format matches the extension\n        # It is possible to upload PSD files if their extension is set to jpg, png or gif. This should catch them out\n        if image.format.upper() != image_format.upper():\n            raise ValidationError(self.error_messages['invalid_image_known_format'] % (\n                image_format.upper()\n            ), code='invalid_image_known_format')\n\n    def check_image_file_size(self, f):\n        # Upload size checking can be disabled by setting max upload size to None\n        if MAX_UPLOAD_SIZE is None:\n            return\n\n        # Check the filesize\n        if f.size > MAX_UPLOAD_SIZE:\n            raise ValidationError(self.error_messages['file_too_large'] % (\n                filesizeformat(f.size),\n            ), code='file_too_large')\n\n    def to_python(self, data):\n        f = super(WagtailImageField, self).to_python(data)\n\n        if f is not None:\n            self.check_image_file_size(f)\n            self.check_image_file_format(f)\n\n        return f\n", "path": "wagtail/wagtailimages/fields.py"}], "after_files": [{"content": "import os\n\nfrom PIL import Image\n\nfrom django.forms.fields import ImageField\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.template.defaultfilters import filesizeformat\nfrom django.conf import settings\n\n\nALLOWED_EXTENSIONS = ['gif', 'jpg', 'jpeg', 'png']\nSUPPORTED_FORMATS_TEXT = _(\"GIF, JPEG, PNG\")\n\nINVALID_IMAGE_ERROR = _(\n    \"Not a supported image format. Supported formats: %s.\"\n) % SUPPORTED_FORMATS_TEXT\n\nINVALID_IMAGE_KNOWN_FORMAT_ERROR = _(\n    \"Not a valid %s image.\"\n)\n\nMAX_UPLOAD_SIZE = getattr(settings, 'WAGTAILIMAGES_MAX_UPLOAD_SIZE', 10 * 1024 * 1024)\n\nif MAX_UPLOAD_SIZE is not None:\n    MAX_UPLOAD_SIZE_TEXT = filesizeformat(MAX_UPLOAD_SIZE)\n\n    FILE_TOO_LARGE_ERROR = _(\n        \"This file is too big. Maximum filesize %s.\"\n    ) % (MAX_UPLOAD_SIZE_TEXT, )\n\n    FILE_TOO_LARGE_KNOWN_SIZE_ERROR = _(\n        \"This file is too big (%%s). Maximum filesize %s.\"\n    ) % (MAX_UPLOAD_SIZE_TEXT, )\n\n    IMAGE_FIELD_HELP_TEXT = _(\n        \"Supported formats: %s. Maximum filesize: %s.\"\n    ) % (SUPPORTED_FORMATS_TEXT, MAX_UPLOAD_SIZE_TEXT, )\nelse:\n    MAX_UPLOAD_SIZE_TEXT = \"\"\n    FILE_TOO_LARGE_ERROR = \"\"\n    FILE_TOO_LARGE_KNOWN_SIZE_ERROR = \"\"\n\n    IMAGE_FIELD_HELP_TEXT = _(\n        \"Supported formats: %s.\"\n    ) % (SUPPORTED_FORMATS_TEXT, )\n\n\nclass WagtailImageField(ImageField):\n    default_error_messages = {\n        'invalid_image': INVALID_IMAGE_ERROR,\n        'invalid_image_known_format': INVALID_IMAGE_KNOWN_FORMAT_ERROR,\n        'file_too_large': FILE_TOO_LARGE_KNOWN_SIZE_ERROR,\n    }\n\n    def __init__(self, *args, **kwargs):\n        super(WagtailImageField, self).__init__(*args, **kwargs)\n\n        self.help_text = IMAGE_FIELD_HELP_TEXT\n\n    def check_image_file_format(self, f):\n        # Check file extension\n        extension = os.path.splitext(f.name)[1].lower()[1:]\n\n        if extension not in ALLOWED_EXTENSIONS:\n            raise ValidationError(self.error_messages['invalid_image'], code='invalid_image')\n\n        if hasattr(f, 'image'):\n            # Django 1.8 annotates the file object with the PIL image\n            image = f.image\n        elif not f.closed:\n            # Open image file\n            file_position = f.tell()\n            f.seek(0)\n\n            try:\n                image = Image.open(f)\n            except IOError:\n                # Uploaded file is not even an image file (or corrupted)\n                raise ValidationError(self.error_messages['invalid_image_known_format'],\n                    code='invalid_image_known_format')\n\n            f.seek(file_position)\n        else:\n            # Couldn't get the PIL image, skip checking the internal file format\n            return\n\n        image_format = extension.upper()\n        if image_format == 'JPG':\n            image_format = 'JPEG'\n\n        internal_image_format = image.format.upper()\n        if internal_image_format == 'MPO':\n            internal_image_format = 'JPEG'\n\n        # Check that the internal format matches the extension\n        # It is possible to upload PSD files if their extension is set to jpg, png or gif. This should catch them out\n        if internal_image_format != image_format:\n            raise ValidationError(self.error_messages['invalid_image_known_format'] % (\n                image_format,\n            ), code='invalid_image_known_format')\n\n    def check_image_file_size(self, f):\n        # Upload size checking can be disabled by setting max upload size to None\n        if MAX_UPLOAD_SIZE is None:\n            return\n\n        # Check the filesize\n        if f.size > MAX_UPLOAD_SIZE:\n            raise ValidationError(self.error_messages['file_too_large'] % (\n                filesizeformat(f.size),\n            ), code='file_too_large')\n\n    def to_python(self, data):\n        f = super(WagtailImageField, self).to_python(data)\n\n        if f is not None:\n            self.check_image_file_size(f)\n            self.check_image_file_format(f)\n\n        return f\n", "path": "wagtail/wagtailimages/fields.py"}]}