internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: python-pillow/Pillow

Issue:
__array_interface__ - get size of image after loading
To be short, I want to ask to one change that do not break any compatibility, and this case is not usual.

Here is what Pillow has now:
https://github.com/python-pillow/Pillow/blob/e7fa3091a065a51ceb7e656b71f67ee587f86082/src/PIL/Image.py#L686-L712

I want to ask to move these lines:
```python3
        shape, typestr = _conv_type_shape(self)
        new["shape"] = shape
        new["typestr"] = typestr
        new["version"] = 3
```
at the end , right after before ``return new``


Reason why it is important to me.
I received such an [issue](https://github.com/bigcat88/pillow_heif/issues/86) where images in `HEIF` format created by **Sony ILCE-7M4** camera has encoded size in itself different from the size value in `HEIF` header. (HEIF format has `size` in header and also `size` of decoded image, and for some unknown reason [they can be different](https://github.com/strukturag/libheif/issues/784))

As I wrote in that issue, I added an optional option ALLOW_INCORRECT_HEADERS(default disabled) that will allow to load such images, and just change the `Image.size` during `load` method.
Tested it, and all seems work well, except this array property, cause here first fills image size in `_conv_type_shape` and after that Image get decoded.

This simple change will do nothing worse, so I will be very appreciated if you agree to move that lines.
Thanks.


Discussion:

Resolving patch:
diff --git a/src/PIL/Image.py b/src/PIL/Image.py
--- a/src/PIL/Image.py
+++ b/src/PIL/Image.py
@@ -686,11 +686,7 @@ def _repr_png_(self):
     @property
     def __array_interface__(self):
         # numpy array interface support
-        new = {}
-        shape, typestr = _conv_type_shape(self)
-        new["shape"] = shape
-        new["typestr"] = typestr
-        new["version"] = 3
+        new = {"version": 3}
         try:
             if self.mode == "1":
                 # Binary images need to be extended from bits to bytes
@@ -709,6 +705,7 @@ def __array_interface__(self):
                     if parse_version(numpy.__version__) < parse_version("1.23"):
                         warnings.warn(e)
             raise
+        new["shape"], new["typestr"] = _conv_type_shape(self)
         return new
 
     def __getstate__(self):


Test patch:
diff --git a/Tests/test_numpy.py b/Tests/test_numpy.py
--- a/Tests/test_numpy.py
+++ b/Tests/test_numpy.py
@@ -4,7 +4,7 @@
 
 from PIL import Image
 
-from .helper import assert_deep_equal, assert_image, hopper
+from .helper import assert_deep_equal, assert_image, hopper, skip_unless_feature
 
 numpy = pytest.importorskip("numpy", reason="NumPy not installed")
 
@@ -219,6 +219,13 @@ def test_zero_size():
     assert im.size == (0, 0)
 
 
+@skip_unless_feature("libtiff")
+def test_load_first():
+    with Image.open("Tests/images/g4_orientation_5.tif") as im:
+        a = numpy.array(im)
+        assert a.shape == (88, 590)
+
+
 def test_bool():
     # https://github.com/python-pillow/Pillow/issues/2044
     a = numpy.zeros((10, 2), dtype=bool)
Repository: python-pillow/Pillow

Issue:
Saving TIFF stack does not support tags with type long8
Title pretty much says it all. 

I believe the problem is that this list doesn't contain long8: [here](https://github.com/python-pillow/Pillow/blob/4ffbbe194c5a1b8840f809574017ab5f1333695f/src/PIL/TiffImagePlugin.py#L1881)

to reproduce
```python
import numpy as np
import PIL
from PIL.TiffImagePlugin import ImageFileDirectory_v2
x = np.ones((2, 10, 10))
pilimgs = [PIL.Image.fromarray(i) for i in x]
ifd = ImageFileDirectory_v2()
ifd[256] = 10
ifd[257] = 10
ifd[65000] = 1234
ifd.tagtype[65000] = 16
pilimgs[0].save("testimgs.tif", save_all=True, tiffinfo=ifd,
                append_images=pilimgs[1:], format="tiff")
```





Discussion:

Resolving patch:
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py
--- a/src/PIL/TiffImagePlugin.py
+++ b/src/PIL/TiffImagePlugin.py
@@ -1892,6 +1892,10 @@ class AppendingTiffWriter:
         8,  # srational
         4,  # float
         8,  # double
+        4,  # ifd
+        2,  # unicode
+        4,  # complex
+        8,  # long8
     ]
 
     #    StripOffsets = 273


Test patch:
diff --git a/Tests/test_file_tiff.py b/Tests/test_file_tiff.py
--- a/Tests/test_file_tiff.py
+++ b/Tests/test_file_tiff.py
@@ -96,10 +96,17 @@ def test_mac_tiff(self):
 
             assert_image_similar_tofile(im, "Tests/images/pil136.png", 1)
 
-    def test_bigtiff(self):
+    def test_bigtiff(self, tmp_path):
         with Image.open("Tests/images/hopper_bigtiff.tif") as im:
             assert_image_equal_tofile(im, "Tests/images/hopper.tif")
 
+        with Image.open("Tests/images/hopper_bigtiff.tif") as im:
+            # multistrip support not yet implemented
+            del im.tag_v2[273]
+
+            outfile = str(tmp_path / "temp.tif")
+            im.save(outfile, save_all=True, append_images=[im], tiffinfo=im.tag_v2)
+
     def test_set_legacy_api(self):
         ifd = TiffImagePlugin.ImageFileDirectory_v2()
         with pytest.raises(Exception) as e:
Repository: python-pillow/Pillow

Issue:
Cannot parse inline stream images, because open() always seeks 0
I am parsing a file format with an inline bitmap. I reached the point at the start of the bitmap and passed the stream to Image.open(). It does a seek(0), which is a default `stream.seek(0,0)` which went to the start of the stream which is not where the bitmap is located.

```python

    try:
        fp.seek(0)
    except (AttributeError, io.UnsupportedOperation):
        fp = io.BytesIO(fp.read())
        exclusive_fp = True
```

I expected that I could pass PIL the opened stream at the start of the file and the stream would be located at the very end of the file. To do this I suspect that:

```python
tell = pf.tell()
fp.seek(tell)
```

Would have been used, and the size of the file would be determined by Pillow knowing the file types.


Worse yet, attempting to use this as an inline reader had the stream seek to the beginning of my reader, issued a false positive error on the read, and said it couldn't parse the image type. After some work on the image it became a bit obvious that it absolutely could parse a super-common 24-bit bitmap, so that message was in error and debugging found this issue.

Without inline stream reading, I needed to read the prefix myself, figure out the size, get that chunk of bytes, wrap those bytes in another `BytesIO()` and submit that.  My workaround seems pretty clumsy looking. And if this was an arbitrary inline image, I might need a lot of different methods to determine the size.
```python

        image_bytes = bytearray(file.read(2))  # BM
        image_length = file.read(4)  # int32le
        (size,) = struct.unpack("<I", image_length)
        image_bytes += image_length
        image_bytes += file.read(size - 6)

        from PIL import Image

        image = Image.open(BytesIO(image_bytes))
```
---

At a minimum, document the fact that streams passed as the `fp` object must have the image located at the beginning of the stream (regardless where the image is located within the stream).


Discussion:

Resolving patch:
diff --git a/src/PIL/Image.py b/src/PIL/Image.py
--- a/src/PIL/Image.py
+++ b/src/PIL/Image.py
@@ -3156,7 +3156,8 @@ def open(fp, mode="r", formats=None):
     :param fp: A filename (string), pathlib.Path object or a file object.
        The file object must implement ``file.read``,
        ``file.seek``, and ``file.tell`` methods,
-       and be opened in binary mode.
+       and be opened in binary mode. The file object will also seek to zero
+       before reading.
     :param mode: The mode.  If given, this argument must be "r".
     :param formats: A list or tuple of formats to attempt to load the file in.
        This can be used to restrict the set of formats checked.


Test patch:
Repository: python-pillow/Pillow

Issue:
ImageFilter.Kernel uses kernel weights in the wrong order?
### What did you do?

I'm using the `ImageFilter.Kernel` filter with a 3x3 kernel that should shift the image down by one pixel, but instead it is shifting the image one pixel up.

I'm assuming the order of weights in the kernel is left-right, top-bottom because, AFAIK, the documentation doesn't specify the order and I assume it uses the same ordering/coordinates as the image itself.

So, this is either a bug in the code, or a bug in the documentation.

### What did you expect to happen?

The image should be shifted one pixel **down**.

### What actually happened?

The image is shifted one pixel **up**.

### What are your OS, Python and Pillow versions?

* OS: CentOS Linux 7.6
* Python: 3.6.7
* Pillow: 5.4.1

```python
from PIL import Image, ImageFilter

shift_down = (
    0, 1, 0,
    0, 0, 0,
    0, 0, 0,
)

original_image = Image.open("images/example.png", mode="r")
filtered_image = original_image.filter(ImageFilter.Kernel((3, 3), shift_down))
filtered_image.save("filtered.png", format="PNG")
```



Discussion:
Additional note, this kernel shifts the image left by one pixel as expected:
```python
shift_left = (
    0, 0, 0,
    0, 0, 1,
    0, 0, 0,
)
```
Possibly related to https://github.com/python-pillow/Pillow/issues/3134?
This can't ever be fixed due to backward compatibility. Think about this as a call convention. The only we can do is update documentation. Pull requests are welcome.

Resolving patch:
diff --git a/src/PIL/ImageFilter.py b/src/PIL/ImageFilter.py
--- a/src/PIL/ImageFilter.py
+++ b/src/PIL/ImageFilter.py
@@ -35,7 +35,7 @@ def filter(self, image):
 
 class Kernel(BuiltinFilter):
     """
-    Create a convolution kernel.  The current version only
+    Create a convolution kernel. The current version only
     supports 3x3 and 5x5 integer and floating point kernels.
 
     In the current version, kernels can only be applied to
@@ -43,9 +43,10 @@ class Kernel(BuiltinFilter):
 
     :param size: Kernel size, given as (width, height). In the current
                     version, this must be (3,3) or (5,5).
-    :param kernel: A sequence containing kernel weights.
+    :param kernel: A sequence containing kernel weights. The kernel will
+                   be flipped vertically before being applied to the image.
     :param scale: Scale factor. If given, the result for each pixel is
-                    divided by this value.  The default is the sum of the
+                    divided by this value. The default is the sum of the
                     kernel weights.
     :param offset: Offset. If given, this value is added to the result,
                     after it has been divided by the scale factor.


Test patch:
Repository: python-pillow/Pillow

Issue:
PIL.ImageGrab.grabclipboard() is lossy on Mac
### Issue

On Mac, `PIL.ImageGrab.grabclipboard()` is lossy because it uses JPG:

```python
commands = [
            'set theFile to (open for access POSIX file "'
            + filepath
            + '" with write permission)',
            "try",
            "    write (the clipboard as JPEG picture) to theFile",
            "end try",
            "close access theFile",
        ]
```

This results in lossy acquisition, which can be highly undesirable.

One such cases is when dealing with screenshots. The noise induced by the JPG conversion on otherwise relatively flat image content eventually leads to much bigger PNG output (if such format is desired in the end).


This can be easily fixed with the following change:

```python
commands = [
            'set theFile to (open for access POSIX file "' + filepath + '" with write permission)',
            "try",
            "    write (the clipboard as «class PNGf») to theFile",
            "end try",
            "close access theFile",
        ]
```

Happy to submit a PR if there is willingness to apply this change.


### What are your OS, Python and Pillow versions?

* OS: macOS Ventura
* Python: 3.11
* Pillow: 9.5



Discussion:
Sure, sounds like a reasonable change. Feel free to create a PR

Resolving patch:
diff --git a/src/PIL/ImageGrab.py b/src/PIL/ImageGrab.py
--- a/src/PIL/ImageGrab.py
+++ b/src/PIL/ImageGrab.py
@@ -95,14 +95,14 @@ def grab(bbox=None, include_layered_windows=False, all_screens=False, xdisplay=N
 
 def grabclipboard():
     if sys.platform == "darwin":
-        fh, filepath = tempfile.mkstemp(".jpg")
+        fh, filepath = tempfile.mkstemp(".png")
         os.close(fh)
         commands = [
             'set theFile to (open for access POSIX file "'
             + filepath
             + '" with write permission)',
             "try",
-            "    write (the clipboard as JPEG picture) to theFile",
+            "    write (the clipboard as «class PNGf») to theFile",
             "end try",
             "close access theFile",
         ]


Test patch:
Repository: python-pillow/Pillow

Issue:
Performance of _repr_png_ with larger images
I've just been using PIL to work with some larger images in IPython/Jupyter (~3k by 2k pixel images) and noticed that it can take a long time (nearly 10 seconds) for them to appear in the output.  I had a poke in the code and found that it's due to `Image._repr_png_` using default compression levels which is causing it to take a significant amount of time.

I tried adding `compress_level=1` to the `save` call which reduces the wait to a couple of seconds–much nicer for interactive use.

I see it's had a recent refactor (in #7135) to also include JPEG support which is nice, but I could put a quick patch together if making this sort of change is considered sensible.


Discussion:

Resolving patch:
diff --git a/src/PIL/Image.py b/src/PIL/Image.py
--- a/src/PIL/Image.py
+++ b/src/PIL/Image.py
@@ -632,7 +632,7 @@ def _repr_pretty_(self, p, cycle):
             )
         )
 
-    def _repr_image(self, image_format):
+    def _repr_image(self, image_format, **kwargs):
         """Helper function for iPython display hook.
 
         :param image_format: Image format.
@@ -640,7 +640,7 @@ def _repr_image(self, image_format):
         """
         b = io.BytesIO()
         try:
-            self.save(b, image_format)
+            self.save(b, image_format, **kwargs)
         except Exception as e:
             msg = f"Could not save to {image_format} for display"
             raise ValueError(msg) from e
@@ -651,7 +651,7 @@ def _repr_png_(self):
 
         :returns: PNG version of the image as bytes
         """
-        return self._repr_image("PNG")
+        return self._repr_image("PNG", compress_level=1)
 
     def _repr_jpeg_(self):
         """iPython display hook support for JPEG format.


Test patch:
Repository: python-pillow/Pillow

Issue:
Enable writing I;16B images as PNG
While investigating an ImageIO issue concerning behavior on big-endian architectures I've noticed that pillow's PNG plugin currently doesn't allow writing 16-bit big-endian images to PNG. `I;16` is already supported, so I was wondering if it would be possible to add `I;16B` as well.

From what I can see, the only change needed to support this would be to add the line `"I;16B": ("I;16B", b"\x10\x00"),` to this dict:

https://github.com/python-pillow/Pillow/blob/3c5324b07c2ed98bc0ec94bd5c6a30f9c66e42fb/src/PIL/PngImagePlugin.py#L1035-L1051

With this change we would be able to do 16 bit round-trips on big-endian, i.e., we can decode the pixel data directly into a 16 bit big-endian buffer and then use that same buffer when encoding as PNG. This would improve performance and streamline working with native encoding on big-endian machines. 


Discussion:

Resolving patch:
diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py
--- a/src/PIL/PngImagePlugin.py
+++ b/src/PIL/PngImagePlugin.py
@@ -1042,6 +1042,7 @@ def getxmp(self):
     "LA": ("LA", b"\x08\x04"),
     "I": ("I;16B", b"\x10\x00"),
     "I;16": ("I;16B", b"\x10\x00"),
+    "I;16B": ("I;16B", b"\x10\x00"),
     "P;1": ("P;1", b"\x01\x03"),
     "P;2": ("P;2", b"\x02\x03"),
     "P;4": ("P;4", b"\x04\x03"),


Test patch:
diff --git a/Tests/test_file_png.py b/Tests/test_file_png.py
--- a/Tests/test_file_png.py
+++ b/Tests/test_file_png.py
@@ -92,11 +92,11 @@ def test_sanity(self, tmp_path):
             assert im.format == "PNG"
             assert im.get_format_mimetype() == "image/png"
 
-        for mode in ["1", "L", "P", "RGB", "I", "I;16"]:
+        for mode in ["1", "L", "P", "RGB", "I", "I;16", "I;16B"]:
             im = hopper(mode)
             im.save(test_file)
             with Image.open(test_file) as reloaded:
-                if mode == "I;16":
+                if mode in ("I;16", "I;16B"):
                     reloaded = reloaded.convert(mode)
                 assert_image_equal(reloaded, im)
Repository: python-pillow/Pillow

Issue:
Bug in QOI decoder leading to corrupted images
### What did you do?

Loaded dice.qoi from the official test image set (https://qoiformat.org/qoi_test_images.zip).

### What did you expect to happen?

Image is not corrupted.

### What actually happened?

Image is corrupted.

### What are your OS, Python and Pillow versions?

* OS: doesn't matter
* Python: doesn't matter
* Pillow: all versions with QOI support

The problem is the faulty implementation of the QOI_OP_RGB operation here https://github.com/python-pillow/Pillow/blob/24606216e1e5931a8fe6f41acde9e7e67489905d/src/PIL/QoiImagePlugin.py#L58C10-L58C10
The implementation sets the alpha channel to 255, however, the QOI specification says it should use the previous alpha value.
Replacing that line with something like `value = self.fd.read(3) + o8(self._previous_pixel[3])` fixes the problem.


Discussion:

Resolving patch:
diff --git a/src/PIL/QoiImagePlugin.py b/src/PIL/QoiImagePlugin.py
--- a/src/PIL/QoiImagePlugin.py
+++ b/src/PIL/QoiImagePlugin.py
@@ -55,7 +55,7 @@ def decode(self, buffer):
         while len(data) < self.state.xsize * self.state.ysize * bands:
             byte = self.fd.read(1)[0]
             if byte == 0b11111110:  # QOI_OP_RGB
-                value = self.fd.read(3) + o8(255)
+                value = self.fd.read(3) + self._previous_pixel[3:]
             elif byte == 0b11111111:  # QOI_OP_RGBA
                 value = self.fd.read(4)
             else:


Test patch:
diff --git a/Tests/test_file_qoi.py b/Tests/test_file_qoi.py
--- a/Tests/test_file_qoi.py
+++ b/Tests/test_file_qoi.py
@@ -2,7 +2,7 @@
 
 from PIL import Image, QoiImagePlugin
 
-from .helper import assert_image_equal_tofile, assert_image_similar_tofile
+from .helper import assert_image_equal_tofile
 
 
 def test_sanity():
@@ -18,7 +18,7 @@ def test_sanity():
         assert im.size == (162, 150)
         assert im.format == "QOI"
 
-        assert_image_similar_tofile(im, "Tests/images/pil123rgba.png", 0.03)
+        assert_image_equal_tofile(im, "Tests/images/pil123rgba.png")
 
 
 def test_invalid_file():
Repository: python-pillow/Pillow

Issue:
Multi-segment Exif fails to read
### What did you do?
Writing code to read ai generated images and tried to get User Comment field from EXIF data contained in an image opened with Image.open. The jpeg image is as far as I can tell not corrupt. ExifTool reads it OK and shows me the comment with a minor warning that "File contains multi-segment EXIF." I can see the User Comment listed in the console with ExifTool. It's large, but looks OK.

### What did you expect to happen?
User Comment field to be read and returned.

### What actually happened?
Using image.getexif().get_ifd(ExifTags.IFD.Exif) returns an empty dict along with this warning on the console-
python3.11/site-packages/PIL/TiffImagePlugin.py:868: UserWarning: Truncated File Read

### What are your OS, Python and Pillow versions?
* OS: Linux pop-os 6.2.6-76060206-generic (Ubuntu compatible with 22 I think)
* Python: 3.11
* Pillow: 10.1.0

```python
with Image.open("03d2695a.jpeg") as i:
    x = i.getexif().get_ifd(ExifTags.IFD.Exif)
```
[03d2695a.jpeg.zip](https://github.com/python-pillow/Pillow/files/13166523/03d2695a.jpeg.zip)




Discussion:

Resolving patch:
diff --git a/src/PIL/JpegImagePlugin.py b/src/PIL/JpegImagePlugin.py
--- a/src/PIL/JpegImagePlugin.py
+++ b/src/PIL/JpegImagePlugin.py
@@ -85,10 +85,12 @@ def APP(self, marker):
                 self.info["dpi"] = jfif_density
             self.info["jfif_unit"] = jfif_unit
             self.info["jfif_density"] = jfif_density
-    elif marker == 0xFFE1 and s[:5] == b"Exif\0":
-        if "exif" not in self.info:
-            # extract EXIF information (incomplete)
-            self.info["exif"] = s  # FIXME: value will change
+    elif marker == 0xFFE1 and s[:6] == b"Exif\0\0":
+        # extract EXIF information
+        if "exif" in self.info:
+            self.info["exif"] += s[6:]
+        else:
+            self.info["exif"] = s
             self._exif_offset = self.fp.tell() - n + 6
     elif marker == 0xFFE2 and s[:5] == b"FPXR\0":
         # extract FlashPix information (incomplete)


Test patch:
diff --git a/Tests/images/multiple_exif.jpg b/Tests/images/multiple_exif.jpg
new file mode 100644
Binary files /dev/null and b/Tests/images/multiple_exif.jpg differ
diff --git a/Tests/test_file_jpeg.py b/Tests/test_file_jpeg.py
--- a/Tests/test_file_jpeg.py
+++ b/Tests/test_file_jpeg.py
@@ -822,6 +822,10 @@ def test_ifd_offset_exif(self):
             # Act / Assert
             assert im._getexif()[306] == "2017:03:13 23:03:09"
 
+    def test_multiple_exif(self):
+        with Image.open("Tests/images/multiple_exif.jpg") as im:
+            assert im.info["exif"] == b"Exif\x00\x00firstsecond"
+
     @mark_if_feature_version(
         pytest.mark.valgrind_known_error, "libjpeg_turbo", "2.0", reason="Known Failing"
     )