Repository: python-pillow/Pillow

Issue:
struct.error: ushort format requires 0 <= number <= (0x7fff * 2 + 1)
[Denia_CORINE_CODE_18_reclass_NLCD92_reproj_ADAPTED_Europe_AEA.tif.zip](https://github.com/python-pillow/Pillow/files/4070890/Denia_CORINE_CODE_18_reclass_NLCD92_reproj_ADAPTED_Europe_AEA.tif.zip)

### What did you do?
I wanted to add the orientation TIFF-Tag with number 274 to my TIFF via the following code:

```python
image = PIL.Image.open(image_path)
image.tag[274] = 1
image.save(save_path, tiffinfo=image.tag, bigtiff=False)
```

### What did you expect to happen?
That the raster image (TIFF) is saved with updated TAGs.

### What actually happened?
When executing the save-command `image.save(save_path, tiffinfo=image.tag, bigtiff=False)`
it threw the following error:
`struct.error: ushort format requires 0 <= number <= (0x7fff * 2 + 1)`.


### Traceback of full-stack error output
```
Traceback (most recent call last):
  File "/home/andylu/Dokumente/Allgemeines_material/Sonstiges/Programming/Python/Scripts/General/GIS_n_image_manipulations.py", line 1131, in change_TIFF_tags_to_desired_values
    image.save(save_path, tiffinfo=image.tag, bigtiff=bigtiff)
  File "/home/andylu/anaconda3/lib/python3.7/site-packages/PIL/Image.py", line 2102, in save
    save_handler(self, fp, filename)
  File "/home/andylu/anaconda3/lib/python3.7/site-packages/PIL/TiffImagePlugin.py", line 1629, in _save
    offset = ifd.save(fp)
  File "/home/andylu/anaconda3/lib/python3.7/site-packages/PIL/TiffImagePlugin.py", line 865, in save
    result = self.tobytes(offset)
  File "/home/andylu/anaconda3/lib/python3.7/site-packages/PIL/TiffImagePlugin.py", line 808, in tobytes
    data = self._write_dispatch[typ](self, *values)
  File "/home/andylu/anaconda3/lib/python3.7/site-packages/PIL/TiffImagePlugin.py", line 644, in <lambda>
    b"".join(self._pack(fmt, value) for value in values)
  File "/home/andylu/anaconda3/lib/python3.7/site-packages/PIL/TiffImagePlugin.py", line 644, in <genexpr>
    b"".join(self._pack(fmt, value) for value in values)
  File "/home/andylu/anaconda3/lib/python3.7/site-packages/PIL/TiffImagePlugin.py", line 611, in _pack
    return struct.pack(self._endian + fmt, *values)
struct.error: ushort format requires 0 <= number <= (0x7fff * 2 + 1)
```

### What are your OS, Python and Pillow versions?

* OS: NAME="Ubuntu"
VERSION="18.04.3 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.3 LTS"
VERSION_ID="18.04"

* Python: Python 3.7.6 (default, Jan  8 2020, 19:59:22) 
[GCC 7.3.0] :: Anaconda, Inc. on linux

* Pillow: pillow                    7.0.0            py37hb39fc2d_0




Discussion:
Please can you include the full error traceback? 
It would also be helpful if you could provide the image that you open at the start.
> It would also be helpful if you could provide the image that you open at the start.

I've just uploaded it within a .zip since I cannot upload .tif - files directly. See edited post.
Thanks! And what's the full error output? 
@hugovk the original post has been edited
> Please can you include the full error traceback?

I've just included it into my original post.
I hope the info I've retrieved via the `traceback` module is what you were after.
It is implemented like this in my python code:

```python
import traceback

try:
    # In my case: image.save(save_path, tiffinfo=image.tag, bigtiff=False)
    something_that_causes_an_error()
except:
    print(traceback.format_exc())
```

Resolving patch:
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py
--- a/src/PIL/TiffImagePlugin.py
+++ b/src/PIL/TiffImagePlugin.py
@@ -1508,7 +1508,10 @@ def _save(im, fp, filename):
     # data orientation
     stride = len(bits) * ((im.size[0] * bits[0] + 7) // 8)
     ifd[ROWSPERSTRIP] = im.size[1]
-    ifd[STRIPBYTECOUNTS] = stride * im.size[1]
+    strip_byte_counts = stride * im.size[1]
+    if strip_byte_counts >= 2 ** 16:
+        ifd.tagtype[STRIPBYTECOUNTS] = TiffTags.LONG
+    ifd[STRIPBYTECOUNTS] = strip_byte_counts
     ifd[STRIPOFFSETS] = 0  # this is adjusted by IFD writer
     # no compression by default:
     ifd[COMPRESSION] = COMPRESSION_INFO_REV.get(compression, 1)


Test patch:
diff --git a/Tests/test_file_tiff_metadata.py b/Tests/test_file_tiff_metadata.py
--- a/Tests/test_file_tiff_metadata.py
+++ b/Tests/test_file_tiff_metadata.py
@@ -156,6 +156,23 @@ def test_write_metadata(tmp_path):
             assert value == reloaded[tag], "%s didn't roundtrip" % tag
 
 
+def test_change_stripbytecounts_tag_type(tmp_path):
+    out = str(tmp_path / "temp.tiff")
+    with Image.open("Tests/images/hopper.tif") as im:
+        info = im.tag_v2
+
+        # Resize the image so that STRIPBYTECOUNTS will be larger than a SHORT
+        im = im.resize((500, 500))
+
+        # STRIPBYTECOUNTS can be a SHORT or a LONG
+        info.tagtype[TiffImagePlugin.STRIPBYTECOUNTS] = TiffTags.SHORT
+
+        im.save(out, tiffinfo=info)
+
+    with Image.open(out) as reloaded:
+        assert reloaded.tag_v2.tagtype[TiffImagePlugin.STRIPBYTECOUNTS] == TiffTags.LONG
+
+
 def test_no_duplicate_50741_tag():
     assert TAG_IDS["MakerNoteSafety"] == 50741
     assert TAG_IDS["BestQualityScale"] == 50780