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

Issue:
ImageTk.getimage is broken
### What did you do?

Looked at the api, tried `ImageTk.getimage`

### What did you expect to happen?

An Image.

### What actually happened?

I got a TkError. Digging through the code, get image calls `tkImaging.c:PyImagingPhotoGet`:
```c
static int
PyImagingPhotoGet(ClientData clientdata, Tcl_Interp* interp,
               int argc, char **argv)
{
    Tk_PhotoHandle photo;
    Tk_PhotoImageBlock block;

    if (argc != 2) {
        Tcl_AppendResult(interp, "usage: ", argv[0],
                         " srcPhoto", (char *) NULL);
        return TCL_ERROR;
    }

    /* get Tcl PhotoImage handle */
    photo = Tk_FindPhoto(interp, argv[1]);
    if (photo == NULL) {
        Tcl_AppendResult(
            interp, "source photo must exist", (char *) NULL
            );
        return TCL_ERROR;
    }

    Tk_PhotoGetImage(photo, &block);

    printf("pixelPtr = %p\n", block.pixelPtr);
    printf("width = %d\n", block.width);
    printf("height = %d\n", block.height);
    printf("pitch = %d\n", block.pitch);
    printf("pixelSize = %d\n", block.pixelSize);
    printf("offset = %d %d %d %d\n", block.offset[0], block.offset[1],
           block.offset[2], block.offset[3]);

    Tcl_AppendResult(
        interp, "this function is not yet supported", (char *) NULL
        );

    return TCL_ERROR;
}
```

Note that every code path ends in an error. 

### What versions of Pillow and Python are you using?

master. But it really doesn't matter, since most of this code hasn't been touched since the PIL import. Except for the Tk reorg. Which didn't actually check that this code could run. 

This code is enough to see the error, added in viewer.py. Other repros are left as an exercise to the reader. 

```python
self.image = ImageTk.PhotoImage(im)
ImageTk.getimage(self.image)
```


Discussion:

Resolving patch:
diff --git a/src/PIL/ImageTk.py b/src/PIL/ImageTk.py
--- a/src/PIL/ImageTk.py
+++ b/src/PIL/ImageTk.py
@@ -275,10 +275,13 @@ def __str__(self):
 
 
 def getimage(photo):
-    """ This function is unimplemented """
-
     """Copies the contents of a PhotoImage to a PIL image memory."""
-    photo.tk.call("PyImagingPhotoGet", photo)
+    im = Image.new("RGBA", (photo.width(), photo.height()))
+    block = im.im
+
+    photo.tk.call("PyImagingPhotoGet", photo, block.id)
+
+    return im
 
 
 def _show(image, title):


Test patch:
diff --git a/Tests/test_imagetk.py b/Tests/test_imagetk.py
--- a/Tests/test_imagetk.py
+++ b/Tests/test_imagetk.py
@@ -61,9 +61,8 @@ def test_photoimage(self):
             self.assertEqual(im_tk.width(), im.width)
             self.assertEqual(im_tk.height(), im.height)
 
-            # _tkinter.TclError: this function is not yet supported
-            # reloaded = ImageTk.getimage(im_tk)
-            # self.assert_image_equal(reloaded, im)
+            reloaded = ImageTk.getimage(im_tk)
+            self.assert_image_equal(reloaded, im.convert("RGBA"))
 
     def test_photoimage_blank(self):
         # test a image using mode/size:
Repository: python-pillow/Pillow

Issue:
On Windows, opening a TIFF with a pathlib.Path argument fails
### What did you do?

1. Create a tiff file (e.g. `from pylab import *; savefig("test.tiff")` using matplotlib).
2. Try to load it with Pillow, passing the path as pathlib.Path: `from PIL import Image; from pathlib import Path; Image.open(Path("test.tiff")).tobytes()`

### What did you expect to happen?

The image is correctly loaded (the same as `Image.open("test.tiff").tobytes()`; using a pathlib.Path also works just fine on Linux).

### What actually happened?

```
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "...\Miniconda3\lib\site-packages\PIL\Image.py", line 746, in tobytes
    self.load()
  File "...\Miniconda3\lib\site-packages\PIL\TiffImagePlugin.py", line 1078, in load
    return super(TiffImageFile, self).load()
  File "...\Miniconda3\lib\site-packages\PIL\ImageFile.py", line 177, in load
    self.map = Image.core.map(self.filename)
TypeError: argument 1 must be str, not WindowsPath
```

### What are your OS, Python and Pillow versions?

* OS: Windows 10
* Python: 3.7
* Pillow: 6.0.0


Discussion:
I wasn't able to replicate this on AppVeyor. I don't suppose you could say if you're only experiencing this on Windows 10, and not Windows 7?

Also, while you would think this should be easy to reproduce in the right environment, could you provide a script from start to end, attaching a file if necessary, without matplotlib?
```python
from pathlib import Path
from PIL import Image

Image.new("RGBA", (100, 100)).save("test.tiff")
Image.open(Path("test.tiff")).tobytes()
```
reproes the bug for me.

I don't have readily access to a win7 machine with python.

This Pillow install is from PyPI, fwiw.
Thanks. I've created PR #3825 to resolve this.

Resolving patch:
diff --git a/src/PIL/Image.py b/src/PIL/Image.py
--- a/src/PIL/Image.py
+++ b/src/PIL/Image.py
@@ -2643,10 +2643,10 @@ def open(fp, mode="r"):
 
     exclusive_fp = False
     filename = ""
-    if isPath(fp):
-        filename = fp
-    elif HAS_PATHLIB and isinstance(fp, Path):
+    if HAS_PATHLIB and isinstance(fp, Path):
         filename = str(fp.resolve())
+    elif isPath(fp):
+        filename = fp
 
     if filename:
         fp = builtins.open(filename, "rb")


Test patch:
diff --git a/Tests/test_image.py b/Tests/test_image.py
--- a/Tests/test_image.py
+++ b/Tests/test_image.py
@@ -76,6 +76,10 @@ def test_bad_mode(self):
     @unittest.skipUnless(Image.HAS_PATHLIB, "requires pathlib/pathlib2")
     def test_pathlib(self):
         from PIL.Image import Path
+        im = Image.open(Path("Tests/images/multipage-mmap.tiff"))
+        self.assertEqual(im.mode, "P")
+        self.assertEqual(im.size, (10, 10))
+
         im = Image.open(Path("Tests/images/hopper.jpg"))
         self.assertEqual(im.mode, "RGB")
         self.assertEqual(im.size, (128, 128))
Repository: python-pillow/Pillow

Issue:
Image.show() uses hardcoded path no longer valid in macOS 10.15
### What did you do?
```Image.show()```

### What did you expect to happen?
Shows image in Preview.app

### What actually happened?
Crashes with invalid path for Preview.app

### What are your OS, Python and Pillow versions?

* OS: macOS 10.15
* Python: Python 3.7.3
* Pillow: 6.0.0

https://github.com/python-pillow/Pillow/blob/f1ed79229ece02a52e4d0df4acda2e26419ea8f4/src/PIL/ImageShow.py#L141

As part of security improvements, operating system is now separated from user data in macOS 10.15, in a read-only volume. [[ref]](https://developer.apple.com/videos/play/wwdc2019/710/)
```/Applications/Preview.app``` is now ```/System/Applications/Preview.app```.


Discussion:
Thanks for testing Pillow with beta macOS! I've created PR #3896 to address this.

Resolving patch:
diff --git a/src/PIL/ImageShow.py b/src/PIL/ImageShow.py
--- a/src/PIL/ImageShow.py
+++ b/src/PIL/ImageShow.py
@@ -128,7 +128,7 @@ class MacViewer(Viewer):
         def get_command(self, file, **options):
             # on darwin open returns immediately resulting in the temp
             # file removal while app is opening
-            command = "open -a /Applications/Preview.app"
+            command = "open -a Preview.app"
             command = "(%s %s; sleep 20; rm -f %s)&" % (
                 command,
                 quote(file),
@@ -143,12 +143,7 @@ def show_file(self, file, **options):
                 f.write(file)
             with open(path, "r") as f:
                 subprocess.Popen(
-                    [
-                        "im=$(cat);"
-                        "open -a /Applications/Preview.app $im;"
-                        "sleep 20;"
-                        "rm -f $im"
-                    ],
+                    ["im=$(cat); open -a Preview.app $im; sleep 20; rm -f $im"],
                     shell=True,
                     stdin=f,
                 )


Test patch:
Repository: python-pillow/Pillow

Issue:
Crash on trying to load corrupted font as file handle
### What did you do?

When loading corrupted file by handle, PIL crashes:

```console
# python -c "from PIL import ImageFont; print(ImageFont.truetype(open('setup.py', 'rb')))"
double free or corruption (top)
Aborted
```

(Originally observed on actually corrupt TTF file, but it as well triggered by non font)

### What did you expect to happen?

Raise an exception

### What actually happened?

Crash (SIGABRT)

### What are your OS, Python and Pillow versions?

* OS: Linux
* Python: 3.7.3
* Pillow: 6.0.0, reproduced with current git master



Discussion:

Resolving patch:
diff --git a/src/PIL/ImageFont.py b/src/PIL/ImageFont.py
--- a/src/PIL/ImageFont.py
+++ b/src/PIL/ImageFont.py
@@ -545,6 +545,8 @@ def freetype(font):
     try:
         return freetype(font)
     except IOError:
+        if not isPath(font):
+            raise
         ttf_filename = os.path.basename(font)
 
         dirs = []


Test patch:
diff --git a/Tests/test_imagefont.py b/Tests/test_imagefont.py
--- a/Tests/test_imagefont.py
+++ b/Tests/test_imagefont.py
@@ -420,6 +420,10 @@ def test_load_path_not_found(self):
         self.assertRaises(IOError, ImageFont.load_path, filename)
         self.assertRaises(IOError, ImageFont.truetype, filename)
 
+    def test_load_non_font_bytes(self):
+        with open("Tests/images/hopper.jpg", "rb") as f:
+            self.assertRaises(IOError, ImageFont.truetype, f)
+
     def test_default_font(self):
         # Arrange
         txt = 'This is a "better than nothing" default font.'
Repository: python-pillow/Pillow

Issue:
BufferedReader wrapping BytesIO breaks tiff loader
I struck an edge case trying to open a TIFF file from a BufferedReader that wraps a BytesIO object. The problem is that when the wrapped object is not a file, BufferedReader has a "fileno" attribute but calling it returns an error. This case is handled for BytesIO itself, and sidestepped by using "getvalue" rather than trying to open by fileno. I'll open a PR but documenting the issue here.

* OS: macOS 10.14.3
* Python: 3.7.3
* Pillow: 6.1.0

```python
import io
from PIL import Image

bytesio = io.BytesIO()
with open(tiff_filename, 'rb') as fp:
    bytesio.write(fp.read())

reader = io.BufferedReader(bytesio)
im = Image.open(reader)
im.load()
```
Result:
```
tempfile.tif: Cannot read TIFF header.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.7/site-packages/PIL/TiffImagePlugin.py", line 1099, in load
    return self._load_libtiff()
  File "/usr/local/lib/python3.7/site-packages/PIL/TiffImagePlugin.py", line 1191, in _load_libtiff
    raise IOError(err)
OSError: -2
```


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
@@ -1164,7 +1164,7 @@ def _load_libtiff(self):
             if DEBUG:
                 print("have getvalue. just sending in a string from getvalue")
             n, err = decoder.decode(self.fp.getvalue())
-        elif hasattr(self.fp, "fileno"):
+        elif fp:
             # we've got a actual file on disk, pass in the fp.
             if DEBUG:
                 print("have fileno, calling fileno version of the decoder.")
@@ -1175,6 +1175,7 @@ def _load_libtiff(self):
             # we have something else.
             if DEBUG:
                 print("don't have fileno or getvalue. just reading")
+            self.fp.seek(0)
             # UNDONE -- so much for that buffer size thing.
             n, err = decoder.decode(self.fp.read())
 


Test patch:
diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py
--- a/Tests/test_file_libtiff.py
+++ b/Tests/test_file_libtiff.py
@@ -81,6 +81,19 @@ def test_g4_tiff_bytesio(self):
         self.assertEqual(im.size, (500, 500))
         self._assert_noerr(im)
 
+    def test_g4_non_disk_file_object(self):
+        """Testing loading from non-disk non-BytesIO file object"""
+        test_file = "Tests/images/hopper_g4_500.tif"
+        s = io.BytesIO()
+        with open(test_file, "rb") as f:
+            s.write(f.read())
+            s.seek(0)
+        r = io.BufferedReader(s)
+        im = Image.open(r)
+
+        self.assertEqual(im.size, (500, 500))
+        self._assert_noerr(im)
+
     def test_g4_eq_png(self):
         """ Checking that we're actually getting the data that we expect"""
         png = Image.open("Tests/images/hopper_bw_500.png")
Repository: python-pillow/Pillow

Issue:
floodfill wraps around
The ImageDraw.floodfill code assumes a negative index will raise an IndexError, but python wraps that around to the last element, which is not the desired effect.  This causes a floodfill that hits the left side or the top of the image to wrap around to the other side.  Code:

```python
                    try:
                        p = pixel[s, t]
                    except (ValueError, IndexError):
                        pass
                    else:
```

Fix:

```python
                    try:
                        if s < 0 or t < 0:
                            raise IndexError
                        p = pixel[s, t]
                    except (ValueError, IndexError):
                        pass
                    else:
```


Discussion:

Resolving patch:
diff --git a/src/PIL/ImageDraw.py b/src/PIL/ImageDraw.py
--- a/src/PIL/ImageDraw.py
+++ b/src/PIL/ImageDraw.py
@@ -437,8 +437,9 @@ def floodfill(image, xy, value, border=None, thresh=0):
         new_edge = set()
         for (x, y) in edge:  # 4 adjacent method
             for (s, t) in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
-                if (s, t) in full_edge:
-                    continue  # if already processed, skip
+                # If already processed, or if a coordinate is negative, skip
+                if (s, t) in full_edge or s < 0 or t < 0:
+                    continue
                 try:
                     p = pixel[s, t]
                 except (ValueError, IndexError):


Test patch:
diff --git a/Tests/images/imagedraw_floodfill_not_negative.png b/Tests/images/imagedraw_floodfill_not_negative.png
new file mode 100644
Binary files /dev/null and b/Tests/images/imagedraw_floodfill_not_negative.png differ
diff --git a/Tests/test_imagedraw.py b/Tests/test_imagedraw.py
--- a/Tests/test_imagedraw.py
+++ b/Tests/test_imagedraw.py
@@ -559,6 +559,24 @@ def test_floodfill_thresh(self):
         # Assert
         self.assert_image_equal(im, Image.open("Tests/images/imagedraw_floodfill2.png"))
 
+    def test_floodfill_not_negative(self):
+        # floodfill() is experimental
+        # Test that floodfill does not extend into negative coordinates
+
+        # Arrange
+        im = Image.new("RGB", (W, H))
+        draw = ImageDraw.Draw(im)
+        draw.line((W / 2, 0, W / 2, H / 2), fill="green")
+        draw.line((0, H / 2, W / 2, H / 2), fill="green")
+
+        # Act
+        ImageDraw.floodfill(im, (int(W / 4), int(H / 4)), ImageColor.getrgb("red"))
+
+        # Assert
+        self.assert_image_equal(
+            im, Image.open("Tests/images/imagedraw_floodfill_not_negative.png")
+        )
+
     def create_base_image_draw(
         self, size, mode=DEFAULT_MODE, background1=WHITE, background2=GRAY
     ):
Repository: python-pillow/Pillow

Issue:
Spider format header bug for random image size
### What did you do?
I am trying to save `float` image in `SPIDER` format

### What did you expect to happen?
I accepted it to work for any image size.

### What actually happened?
The saved spider file has corrupt header when the width of the image is not a power of 2. 

### What are your OS, Python and Pillow versions?

* OS: Windows 10 
* Python: 3.6
* Pillow: 6.1.1

```python
from PIL import Image
import numpy as np

filename= "im.spi"
width = 100  # change it to any natural number not a power of 2
im = np.random.random((64, width))-1
pil_image = Image.fromarray(im, 'F')
pil_image.save(filename, format='SPIDER')

im2 = Image.open(filename)
print(im2.size)
```

I was able to trace the bug to [this](https://github.com/python-pillow/Pillow/blob/master/src/PIL/SpiderImagePlugin.py#L239) line.
Changing the line from `labrec = 1024 / lenbyt` to `labrec = int(1024 / lenbyt)` fixes the bug for me. 



Discussion:

Resolving patch:
diff --git a/src/PIL/SpiderImagePlugin.py b/src/PIL/SpiderImagePlugin.py
--- a/src/PIL/SpiderImagePlugin.py
+++ b/src/PIL/SpiderImagePlugin.py
@@ -236,7 +236,7 @@ def loadImageSeries(filelist=None):
 def makeSpiderHeader(im):
     nsam, nrow = im.size
     lenbyt = nsam * 4  # There are labrec records in the header
-    labrec = 1024 / lenbyt
+    labrec = int(1024 / lenbyt)
     if 1024 % lenbyt != 0:
         labrec += 1
     labbyt = labrec * lenbyt


Test patch:
diff --git a/Tests/test_file_spider.py b/Tests/test_file_spider.py
--- a/Tests/test_file_spider.py
+++ b/Tests/test_file_spider.py
@@ -1,4 +1,5 @@
 import tempfile
+from io import BytesIO
 
 from PIL import Image, ImageSequence, SpiderImagePlugin
 
@@ -117,3 +118,14 @@ def test_nonstack_dos(self):
         for i, frame in enumerate(ImageSequence.Iterator(im)):
             if i > 1:
                 self.fail("Non-stack DOS file test failed")
+
+    # for issue #4093
+    def test_odd_size(self):
+        data = BytesIO()
+        width = 100
+        im = Image.new("F", (width, 64))
+        im.save(data, format="SPIDER")
+
+        data.seek(0)
+        im2 = Image.open(data)
+        self.assert_image_equal(im, im2)
Repository: python-pillow/Pillow

Issue:
Pillow 6.2 fails to open JPEG image with corrupted Photoshop metadata
### What did you do?
Tried to open a .jpg image with PIL.

### What did you expect to happen?
The photo can be opened in a browser and by IrfanView (v4.53, 64bit, Windows 7).

### What actually happened?
```python
from PIL import Image
Image.open("test.jpg")
```

```
File "testFIL.py", line 3, in <module>
  im = Image.open("test.jpg")
File "/home/fe/stallenberger/anaconda3/envs/pillow/lib/python3.8/site-packages/PIL/Images.py", line 2818, in open
  raise IOError("cannot identify image file %r" % (filename if filename else fp))
OSError: cannot identify image file 'test.jpg'
```

### What are your OS, Python and Pillow versions?
    OS: Scientific Linux release 7.7 (Nitrogen)
    Python: 3.8.0
    Pillow: 6.2

### Image file
![test](https://user-images.githubusercontent.com/58255551/69719202-46036d00-1110-11ea-8cff-594225f7e49c.jpg)

For this particular image, the PhotoShop metadata (APP13 segment) seems to be corrupted since it ends with "8BIM". Normally, this tag introduces an Image Resource Block but in this particular file there is no data following in the APP13 segment. Thus, parsing this block of metadata and therefore opening the image fails.

Opening the image in Pillow 5.3.0 works well, since this version ignores the APP13 segment.



Discussion:
Thanks for reporting this. Is the image that you've supplied one that can be included in the test suite, and distributed under the Pillow license?

Resolving patch:
diff --git a/src/PIL/JpegImagePlugin.py b/src/PIL/JpegImagePlugin.py
--- a/src/PIL/JpegImagePlugin.py
+++ b/src/PIL/JpegImagePlugin.py
@@ -109,7 +109,10 @@ def APP(self, marker):
             while blocks[offset : offset + 4] == b"8BIM":
                 offset += 4
                 # resource code
-                code = i16(blocks, offset)
+                try:
+                    code = i16(blocks, offset)
+                except struct.error:
+                    break
                 offset += 2
                 # resource name (usually empty)
                 name_len = i8(blocks[offset])


Test patch:
diff --git a/Tests/images/photoshop-200dpi-broken.jpg b/Tests/images/photoshop-200dpi-broken.jpg
new file mode 100644
Binary files /dev/null and b/Tests/images/photoshop-200dpi-broken.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
@@ -656,6 +656,11 @@ def test_photoshop(self):
                 },
             )
 
+            # Test that the image can still load, even with broken Photoshop data
+            # This image had the APP13 length hexedited to be smaller
+            with Image.open("Tests/images/photoshop-200dpi-broken.jpg") as im_broken:
+                self.assert_image_equal(im_broken, im)
+
         # This image does not contain a Photoshop header string
         with Image.open("Tests/images/app13.jpg") as im:
             self.assertNotIn("photoshop", im.info)
Repository: python-pillow/Pillow

Issue:
PIL cannot read JPEG comment
### What did you do?
I want PIL to read the JPEG comment (marker: 0xFF 0xFE).  
  
I took an image with an attached JPEG comment - verified with exiftools & IrfanView to exist.

```python
from PIL import Image, JpegImagePlugin
pic = Image.open(<path_to_pic_with_JPEG_comment>)
print(pic.info)
```

### What did you expect to happen?
Show the JPEG comment in the dict.

### What actually happened?
> {'jfif': 257, 'jfif_version': (1, 1), 'dpi': (96, 96), 'jfif_unit': 1, 'jfif_density': (96, 96), 'exif': b'...'}


### What are your OS, Python and Pillow versions?

* OS: W7x64
* Python: Python 3.8.1 x64
* Pillow: Pillow           7.0.0

I cannot attach an image via github ("Something went really wrong, ..."), so here is the file (5.61 KiB) (I downloaded it and verified it's byte-identical to the uploaded one): [![jpeg-comment-test.jpg](https://i.postimg.cc/nrz1xV1r/jpeg-comment-test.jpg)](https://postimg.cc/BLrFc0kf)


Discussion:
It's not exposed under `info` right now, but could be easily added in https://github.com/python-pillow/Pillow/blob/master/src/PIL/JpegImagePlugin.py#L180 
Yes, for the moment, you can access it through
```python
from PIL import Image
im = Image.open("comment.jpg")
print(im.app["COM"])  # b'JPEG-COMMENT-TEST\x00'
```
I've created PR #4455 to resolve this.
Thank you both.

Resolving patch:
diff --git a/src/PIL/JpegImagePlugin.py b/src/PIL/JpegImagePlugin.py
--- a/src/PIL/JpegImagePlugin.py
+++ b/src/PIL/JpegImagePlugin.py
@@ -176,6 +176,7 @@ def COM(self, marker):
     n = i16(self.fp.read(2)) - 2
     s = ImageFile._safe_read(self.fp, n)
 
+    self.info["comment"] = s
     self.app["COM"] = s  # compatibility
     self.applist.append(("COM", s))
 


Test patch:
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
@@ -60,6 +60,8 @@ def test_app(self):
             )
             assert len(im.applist) == 2
 
+            assert im.info["comment"] == b"File written by Adobe Photoshop\xa8 4.0\x00"
+
     def test_cmyk(self):
         # Test CMYK handling.  Thanks to Tim and Charlie for test data,
         # Michael for getting me to look one more time.