Repository: python-pillow/Pillow

Issue:
Incorrect JPEG EXIF write
<!--
Thank you for reporting an issue.

Follow these guidelines to ensure your issue is handled properly.

If you have a ...

1.  General question: consider asking the question on Stack Overflow
    with the python-imaging-library tag:

    * https://stackoverflow.com/questions/tagged/python-imaging-library

    Do not ask a question in both places.

    If you think you have found a bug or have an unexplained exception
    then file a bug report here.

2.  Bug report: include a self-contained, copy-pastable example that
    generates the issue if possible. Be concise with code posted.
    Guidelines on how to provide a good bug report:

    * https://stackoverflow.com/help/mcve

    Bug reports which follow these guidelines are easier to diagnose,
    and are often handled much more quickly.

3.  Feature request: do a quick search of existing issues
    to make sure this has not been asked before.

We know asking good questions takes effort, and we appreciate your time.
Thank you.
-->

### What did you do?

Open an image with, save it with its exif data.

### What did you expect to happen?

The content of the exif in both image should be the same using standard tool like `exiftool`.

### What actually happened?

Some fields raise a parsing waning in exiftool (ie `CFAPattern`), and other have their value changed (ie `ExifVersion`).

### What are your OS, Python and Pillow versions?

* OS: Ubuntu 20.04
* Python: 3.8.5
* Pillow: 8.2.0

<!--
Please include **code** that reproduces the issue and whenever possible, an **image** that demonstrates the issue. Please upload images to GitHub, not to third-party file hosting sites. If necessary, add the image to a zip or tar archive.

The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as Plone, Django, or Buildout, try to replicate the issue just using Pillow.
-->

```python
from PIL import Image
#open a jpeg image
im = Image.open("/tmp/img_original.jpg")
# save it with original parameters, but it doesn't change the problem to use default values
im.save("/tmp/as_is.jpg", exif=im.getexif(), quality=95, progressive=True, subsampling="4:4:4")
```

input image:
![img_original](https://user-images.githubusercontent.com/4659733/117844262-d3dd0480-b27f-11eb-8c2e-3e580bf25ff0.jpg)

Output image:
![as_is](https://user-images.githubusercontent.com/4659733/117844297-dc353f80-b27f-11eb-9acd-7eb9e8ca951d.jpg)

Input exif (extracted using `exiftool -s img_original.jpg > original.exif`):
```
ExifToolVersion                 : 11.88
FileName                        : img_original.jpg
Directory                       : .
FileSize                        : 38 kB
FileModifyDate                  : 2021:05:11 17:22:33+02:00
FileAccessDate                  : 2021:05:11 17:22:59+02:00
FileInodeChangeDate             : 2021:05:11 17:22:33+02:00
FilePermissions                 : rw-rw-r--
FileType                        : JPEG
FileTypeExtension               : jpg
MIMEType                        : image/jpeg
JFIFVersion                     : 1.01
ExifByteOrder                   : Little-endian (Intel, II)
ImageDescription                : 1056 783
Make                            : REDACTED
Model                           : REDACTED
Orientation                     : Horizontal (normal)
XResolution                     : 300
YResolution                     : 300
ResolutionUnit                  : inches
Software                        : GIMP 2.10.18
ModifyDate                      : 2021:05:11 17:20:27
Copyright                       : REDACTED
ExposureTime                    : 1/1106
ExposureProgram                 : Not Defined
ISO                             : 100
ExifVersion                     : 0230
DateTimeOriginal                : 2021:04:29 16:00:00
ComponentsConfiguration         : Y, Cb, Cr, -
BrightnessValue                 : 1
SubjectDistance                 : 0 m
MeteringMode                    : Unknown
LightSource                     : Unknown
Flash                           : No Flash
UserComment                     : 1056 783
FlashpixVersion                 : 0100
ColorSpace                      : sRGB
ExifImageWidth                  : 1920
ExifImageHeight                 : 692
SensingMethod                   : One-chip color area
SceneType                       : Directly photographed
CFAPattern                      : [Red,Green][Green,Blue]
CustomRendered                  : Normal
WhiteBalance                    : Auto
GainControl                     : None
Contrast                        : Normal
Saturation                      : Normal
Sharpness                       : Normal
SubjectDistanceRange            : Unknown
GPSVersionID                    : 0.0.2.3
GPSLatitudeRef                  : North
GPSLongitudeRef                 : East
GPSTimeStamp                    : 07:31:14
GPSDateStamp                    : 2021:31:26
Compression                     : JPEG (old-style)
PhotometricInterpretation       : YCbCr
SamplesPerPixel                 : 3
ThumbnailOffset                 : 1062
ThumbnailLength                 : 4486
ProfileCMMType                  : Little CMS
ProfileVersion                  : 4.3.0
ProfileClass                    : Display Device Profile
ColorSpaceData                  : RGB
ProfileConnectionSpace          : XYZ
ProfileDateTime                 : 2021:05:11 15:20:00
ProfileFileSignature            : acsp
PrimaryPlatform                 : Apple Computer Inc.
CMMFlags                        : Not Embedded, Independent
DeviceManufacturer              : 
DeviceModel                     : 
DeviceAttributes                : Reflective, Glossy, Positive, Color
RenderingIntent                 : Perceptual
ConnectionSpaceIlluminant       : 0.9642 1 0.82491
ProfileCreator                  : Little CMS
ProfileID                       : 0
ProfileDescription              : GIMP built-in sRGB
ProfileCopyright                : Public Domain
MediaWhitePoint                 : 0.9642 1 0.82491
ChromaticAdaptation             : 1.04788 0.02292 -0.05022 0.02959 0.99048 -0.01707 -0.00925 0.01508 0.75168
RedMatrixColumn                 : 0.43604 0.22249 0.01392
BlueMatrixColumn                : 0.14305 0.06061 0.71393
GreenMatrixColumn               : 0.38512 0.7169 0.09706
RedTRC                          : (Binary data 32 bytes, use -b option to extract)
GreenTRC                        : (Binary data 32 bytes, use -b option to extract)
BlueTRC                         : (Binary data 32 bytes, use -b option to extract)
ChromaticityChannels            : 3
ChromaticityColorant            : Unknown (0)
ChromaticityChannel1            : 0.64 0.33002
ChromaticityChannel2            : 0.3 0.60001
ChromaticityChannel3            : 0.15001 0.06
DeviceMfgDesc                   : GIMP
DeviceModelDesc                 : sRGB
Comment                         : 1056 783
ImageWidth                      : 1920
ImageHeight                     : 692
EncodingProcess                 : Progressive DCT, Huffman coding
BitsPerSample                   : 8
ColorComponents                 : 3
YCbCrSubSampling                : YCbCr4:4:4 (1 1)
ImageSize                       : 1920x692
Megapixels                      : 1.3
ShutterSpeed                    : 1/1106
ThumbnailImage                  : (Binary data 4486 bytes, use -b option to extract)
GPSDateTime                     : 2021:31:26 07:31:14Z
GPSLatitude                     : 48 deg 42' 40.32" N
GPSLongitude                    : 6 deg 10' 26.76" E
GPSPosition                     : 48 deg 42' 40.32" N, 6 deg 10' 26.76" E
```

Output EXIF:
```
ExifToolVersion                 : 11.88
FileName                        : as_is.jpg
Directory                       : .
FileSize                        : 33 kB
FileModifyDate                  : 2021:05:11 17:30:28+02:00
FileAccessDate                  : 2021:05:11 17:30:28+02:00
FileInodeChangeDate             : 2021:05:11 17:30:28+02:00
FilePermissions                 : rw-rw-r--
FileType                        : JPEG
FileTypeExtension               : jpg
MIMEType                        : image/jpeg
JFIFVersion                     : 1.01
ExifByteOrder                   : Little-endian (Intel, II)
ImageDescription                : 1056 783
Make                            : REDACTED
Model                           : REDACTED
Orientation                     : Horizontal (normal)
XResolution                     : 300
YResolution                     : 300
ResolutionUnit                  : inches
Software                        : GIMP 2.10.18
ModifyDate                      : 2021:05:11 17:20:27
Copyright                       : REDACTED
ExposureTime                    : 1/1106
ExposureProgram                 : Not Defined
ISO                             : 100
ExifVersion                     : 48 50 51 48
DateTimeOriginal                : 2021:04:29 16:00:00
ComponentsConfiguration         : Y, Cb, Cr, -
BrightnessValue                 : 1
SubjectDistance                 : 0 m
MeteringMode                    : Unknown
LightSource                     : Unknown
Flash                           : No Flash
UserComment                     : 1056 783
FlashpixVersion                 : 48 49 48 48
ColorSpace                      : sRGB
ExifImageWidth                  : 1920
ExifImageHeight                 : 692
SensingMethod                   : One-chip color area
SceneType                       : Directly photographed
Warning                         : [minor] Invalid CFAPattern
CFAPattern                      : <invalid pattern size>
CustomRendered                  : Normal
WhiteBalance                    : Auto
GainControl                     : None
Contrast                        : Normal
Saturation                      : Normal
Sharpness                       : Normal
SubjectDistanceRange            : Unknown
GPSVersionID                    : 0.0.2.3
GPSLatitudeRef                  : North
GPSLongitudeRef                 : East
GPSTimeStamp                    : 07:31:14
GPSDateStamp                    : 2021:31:26
ImageWidth                      : 1920
ImageHeight                     : 692
EncodingProcess                 : Progressive DCT, Huffman coding
BitsPerSample                   : 8
ColorComponents                 : 3
YCbCrSubSampling                : YCbCr4:4:4 (1 1)
ImageSize                       : 1920x692
Megapixels                      : 1.3
ShutterSpeed                    : 1/1106
GPSDateTime                     : 2021:31:26 07:31:14Z
GPSLatitude                     : 48 deg 42' 40.32" N
GPSLongitude                    : 6 deg 10' 26.76" E
GPSPosition                     : 48 deg 42' 40.32" N, 6 deg 10' 26.76" E
```





Discussion:

Resolving patch:
diff --git a/src/PIL/TiffTags.py b/src/PIL/TiffTags.py
--- a/src/PIL/TiffTags.py
+++ b/src/PIL/TiffTags.py
@@ -184,7 +184,9 @@ def lookup(tag):
     34665: ("ExifIFD", LONG, 1),
     34675: ("ICCProfile", UNDEFINED, 1),
     34853: ("GPSInfoIFD", LONG, 1),
+    36864: ("ExifVersion", UNDEFINED, 1),
     40965: ("InteroperabilityIFD", LONG, 1),
+    41730: ("CFAPattern", UNDEFINED, 1),
     # MPInfo
     45056: ("MPFVersion", UNDEFINED, 1),
     45057: ("NumberOfImages", LONG, 1),
@@ -205,6 +207,7 @@ def lookup(tag):
     45579: ("YawAngle", SIGNED_RATIONAL, 1),
     45580: ("PitchAngle", SIGNED_RATIONAL, 1),
     45581: ("RollAngle", SIGNED_RATIONAL, 1),
+    40960: ("FlashPixVersion", UNDEFINED, 1),
     50741: ("MakerNoteSafety", SHORT, 1, {"Unsafe": 0, "Safe": 1}),
     50780: ("BestQualityScale", RATIONAL, 1),
     50838: ("ImageJMetaDataByteCounts", LONG, 0),  # Can be more than one


Test patch: