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

Issue:
Exposing the OpenJPEG sgnd parameter when JPEG2000 encoding 
I'd like to be able to perform JPEG2K encoding of medical images using Pillow, particularly 16-bit signed greyscale (commonly used with CT and MR). Because of the limited supported `modes` in `Jpeg2KEncode.c` this is not currently possible as all input data is [treated as unsigned](https://github.com/python-pillow/Pillow/blob/eed337eacc58bb77b1d20c194507693ed4a40a80/src/libImaging/Jpeg2KEncode.c#L345).

Would it be acceptable if I provided a PR exposing the `sgnd` compression parameter to end users when saving? I ask because it feels more like a workaround than a true solution. Ideally I'd add support for `I` mode but OpenJPEG only supports a maximum of 31 bit samples.


Discussion:
I've created PR #6709 to resolve this by exposing the `sgnd` parameter.

Resolving patch:
diff --git a/src/PIL/Jpeg2KImagePlugin.py b/src/PIL/Jpeg2KImagePlugin.py
--- a/src/PIL/Jpeg2KImagePlugin.py
+++ b/src/PIL/Jpeg2KImagePlugin.py
@@ -321,6 +321,7 @@ def _save(im, fp, filename):
     progression = info.get("progression", "LRCP")
     cinema_mode = info.get("cinema_mode", "no")
     mct = info.get("mct", 0)
+    signed = info.get("signed", False)
     fd = -1
 
     if hasattr(fp, "fileno"):
@@ -342,6 +343,7 @@ def _save(im, fp, filename):
         progression,
         cinema_mode,
         mct,
+        signed,
         fd,
     )
 


Test patch:
diff --git a/Tests/test_file_jpeg2k.py b/Tests/test_file_jpeg2k.py
--- a/Tests/test_file_jpeg2k.py
+++ b/Tests/test_file_jpeg2k.py
@@ -252,6 +252,20 @@ def test_mct():
             assert_image_similar(im, jp2, 1.0e-3)
 
 
+def test_sgnd(tmp_path):
+    outfile = str(tmp_path / "temp.jp2")
+
+    im = Image.new("L", (1, 1))
+    im.save(outfile)
+    with Image.open(outfile) as reloaded:
+        assert reloaded.getpixel((0, 0)) == 0
+
+    im = Image.new("L", (1, 1))
+    im.save(outfile, signed=True)
+    with Image.open(outfile) as reloaded_signed:
+        assert reloaded_signed.getpixel((0, 0)) == 128
+
+
 def test_rgba():
     # Arrange
     with Image.open("Tests/images/rgb_trns_ycbc.j2k") as j2k:
Repository: python-pillow/Pillow

Issue:
Can we get `getxmp` method for WebP images?
PNG, Jpeg and TIFF already have this method.
IMHO, it would be nice to add such a thing to WebP.

```python
Image.open("image.webp").getxmp()
```

I know it's stored in `info["xmp"]`, but a generic method would be more convenient.


Discussion:
I've created PR #6758 to resolve this.

Resolving patch:
diff --git a/src/PIL/WebPImagePlugin.py b/src/PIL/WebPImagePlugin.py
--- a/src/PIL/WebPImagePlugin.py
+++ b/src/PIL/WebPImagePlugin.py
@@ -98,6 +98,15 @@ def _getexif(self):
             return None
         return self.getexif()._get_merged_dict()
 
+    def getxmp(self):
+        """
+        Returns a dictionary containing the XMP tags.
+        Requires defusedxml to be installed.
+
+        :returns: XMP tags in a dictionary.
+        """
+        return self._getxmp(self.info["xmp"]) if "xmp" in self.info else {}
+
     def seek(self, frame):
         if not self._seek_check(frame):
             return


Test patch:
diff --git a/Tests/test_file_webp_metadata.py b/Tests/test_file_webp_metadata.py
--- a/Tests/test_file_webp_metadata.py
+++ b/Tests/test_file_webp_metadata.py
@@ -11,6 +11,11 @@
     skip_unless_feature("webp_mux"),
 ]
 
+try:
+    from defusedxml import ElementTree
+except ImportError:
+    ElementTree = None
+
 
 def test_read_exif_metadata():
 
@@ -110,6 +115,22 @@ def test_read_no_exif():
         assert not webp_image._getexif()
 
 
+def test_getxmp():
+    with Image.open("Tests/images/flower.webp") as im:
+        assert "xmp" not in im.info
+        assert im.getxmp() == {}
+
+    with Image.open("Tests/images/flower2.webp") as im:
+        if ElementTree is None:
+            with pytest.warns(UserWarning):
+                assert im.getxmp() == {}
+        else:
+            assert (
+                im.getxmp()["xmpmeta"]["xmptk"]
+                == "Adobe XMP Core 5.3-c011 66.145661, 2012/02/06-14:56:27        "
+            )
+
+
 @skip_unless_feature("webp_anim")
 def test_write_animated_metadata(tmp_path):
     iccp_data = b"<iccp_data>"
Repository: python-pillow/Pillow

Issue:
ValueError: cannot add non-opaque RGBA color to RGB palette
This image: [dancing.zip](https://github.com/python-pillow/Pillow/files/10189483/dancing.zip)

Testcase:
````python
import PIL.Image
with PIL.Image.open('dancing.webp') as img:
    assert img.mode == 'RGB'
    frames = []
    for frame in PIL.ImageSequence.Iterator(img):
        frame = frame.resize( img.size, PIL.Image.BICUBIC )
        assert frame.mode == 'RGB'
        frames.append( frame )
    frames[0].save( 'result.gif', format='GIF', version='GIF89a', save_all=True, append_images=frames[1:], duration=30, loop=0 )
````


Discussion:
I've created PR #6792 to resolve this.

Resolving patch:
diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py
--- a/src/PIL/GifImagePlugin.py
+++ b/src/PIL/GifImagePlugin.py
@@ -886,20 +886,23 @@ def _get_palette_bytes(im):
 def _get_background(im, info_background):
     background = 0
     if info_background:
-        background = info_background
-        if isinstance(background, tuple):
+        if isinstance(info_background, tuple):
             # WebPImagePlugin stores an RGBA value in info["background"]
             # So it must be converted to the same format as GifImagePlugin's
             # info["background"] - a global color table index
             try:
-                background = im.palette.getcolor(background, im)
+                background = im.palette.getcolor(info_background, im)
             except ValueError as e:
-                if str(e) == "cannot allocate more than 256 colors":
+                if str(e) not in (
                     # If all 256 colors are in use,
                     # then there is no need for the background color
-                    return 0
-                else:
+                    "cannot allocate more than 256 colors",
+                    # Ignore non-opaque WebP background
+                    "cannot add non-opaque RGBA color to RGB palette",
+                ):
                     raise
+        else:
+            background = info_background
     return background
 
 


Test patch:
diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py
--- a/Tests/test_file_gif.py
+++ b/Tests/test_file_gif.py
@@ -859,14 +859,23 @@ def test_background(tmp_path):
     im.info["background"] = 1
     im.save(out)
     with Image.open(out) as reread:
-
         assert reread.info["background"] == im.info["background"]
 
+
+def test_webp_background(tmp_path):
+    out = str(tmp_path / "temp.gif")
+
+    # Test opaque WebP background
     if features.check("webp") and features.check("webp_anim"):
         with Image.open("Tests/images/hopper.webp") as im:
-            assert isinstance(im.info["background"], tuple)
+            assert im.info["background"] == (255, 255, 255, 255)
             im.save(out)
 
+    # Test non-opaque WebP background
+    im = Image.new("L", (100, 100), "#000")
+    im.info["background"] = (0, 0, 0, 0)
+    im.save(out)
+
 
 def test_comment(tmp_path):
     with Image.open(TEST_GIF) as im:
Repository: python-pillow/Pillow

Issue:
AttributeError: 'int' object has no attribute 'encode'
This image:  ![rotateexif](https://user-images.githubusercontent.com/274624/207291409-c2d12ce9-14b6-4f2c-bfb4-57455c6ed290.jpg)

Testcase:
 ````python
import PIL.Image
with PIL.Image.open('/tmp/rotateexif.jpg') as img:
    PIL.ImageOps.exif_transpose( img )
````



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
@@ -732,6 +732,8 @@ def load_string(self, data, legacy_api=True):
     @_register_writer(2)
     def write_string(self, value):
         # remerge of https://github.com/python-pillow/Pillow/pull/1416
+        if isinstance(value, int):
+            value = str(value)
         if not isinstance(value, bytes):
             value = value.encode("ascii", "replace")
         return value + b"\0"


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
@@ -185,20 +185,21 @@ def test_iptc(tmp_path):
         im.save(out)
 
 
-def test_writing_bytes_to_ascii(tmp_path):
-    im = hopper()
+@pytest.mark.parametrize("value, expected", ((b"test", "test"), (1, "1")))
+def test_writing_other_types_to_ascii(value, expected, tmp_path):
     info = TiffImagePlugin.ImageFileDirectory_v2()
 
     tag = TiffTags.TAGS_V2[271]
     assert tag.type == TiffTags.ASCII
 
-    info[271] = b"test"
+    info[271] = value
 
+    im = hopper()
     out = str(tmp_path / "temp.tiff")
     im.save(out, tiffinfo=info)
 
     with Image.open(out) as reloaded:
-        assert reloaded.tag_v2[271] == "test"
+        assert reloaded.tag_v2[271] == expected
 
 
 def test_writing_int_to_bytes(tmp_path):
Repository: python-pillow/Pillow

Issue:
Deprecated filters listed on "concepts" page
https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-filters
https://pillow.readthedocs.io/en/stable/reference/Image.html#resampling-filters

The "concepts" page lists the `PIL.Image.X` names for the filters, but it should actually use `PIL.Image.Resampling.X`.


Discussion:
As of Pillow 9.4.0, they are actually no longer deprecated - https://pillow.readthedocs.io/en/stable/releasenotes/9.4.0.html#constants

But we should be consistent in what we talk about in the documentation. I've created PR #6868 to resolve this

Resolving patch:
diff --git a/src/PIL/ImageOps.py b/src/PIL/ImageOps.py
--- a/src/PIL/ImageOps.py
+++ b/src/PIL/ImageOps.py
@@ -248,7 +248,8 @@ def contain(image, size, method=Image.Resampling.BICUBIC):
     :param size: The requested output size in pixels, given as a
                  (width, height) tuple.
     :param method: Resampling method to use. Default is
-                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.
+                   :py:attr:`~PIL.Image.Resampling.BICUBIC`.
+                   See :ref:`concept-filters`.
     :return: An image.
     """
 
@@ -276,7 +277,8 @@ def pad(image, size, method=Image.Resampling.BICUBIC, color=None, centering=(0.5
     :param size: The requested output size in pixels, given as a
                  (width, height) tuple.
     :param method: Resampling method to use. Default is
-                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.
+                   :py:attr:`~PIL.Image.Resampling.BICUBIC`.
+                   See :ref:`concept-filters`.
     :param color: The background color of the padded image.
     :param centering: Control the position of the original image within the
                       padded version.
@@ -328,7 +330,8 @@ def scale(image, factor, resample=Image.Resampling.BICUBIC):
     :param image: The image to rescale.
     :param factor: The expansion factor, as a float.
     :param resample: Resampling method to use. Default is
-                     :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.
+                     :py:attr:`~PIL.Image.Resampling.BICUBIC`.
+                     See :ref:`concept-filters`.
     :returns: An :py:class:`~PIL.Image.Image` object.
     """
     if factor == 1:
@@ -425,7 +428,8 @@ def fit(image, size, method=Image.Resampling.BICUBIC, bleed=0.0, centering=(0.5,
     :param size: The requested output size in pixels, given as a
                  (width, height) tuple.
     :param method: Resampling method to use. Default is
-                   :py:attr:`PIL.Image.BICUBIC`. See :ref:`concept-filters`.
+                   :py:attr:`~PIL.Image.Resampling.BICUBIC`.
+                   See :ref:`concept-filters`.
     :param bleed: Remove a border around the outside of the image from all
                   four edges. The value is a decimal percentage (use 0.01 for
                   one percent). The default value is 0 (no border).


Test patch:
Repository: python-pillow/Pillow

Issue:
Fatal Python error for negative radius in ImageFilter.BoxBlur()
Hi,

Python crashes without an exception when a negative radius is passed into ImageFilter.BoxBlur().
This is the error message using spyder.

```
Fatal Python error: Aborted

Main thread:
Current thread 0x00007fbab679b740 (most recent call first):
  File "/home/mgouka/miniconda3/envs/bx_gui/lib/python3.9/site-packages/PIL/ImageFilter.py", line 189 in filter
  File "/home/mgouka/miniconda3/envs/bx_gui/lib/python3.9/site-packages/PIL/Image.py", line 1305 in filter
  File "/tmp/ipykernel_28079/2108891280.py", line 1 in <module>


Restarting kernel...
```

And using python in the standard linux terminal it says:

```
Segmentation fault (core dumped)
```

The code below produces the problem.

```python
import numpy as np
from PIL import Image, ImageFilter

img = Image.fromarray(np.ones([100, 100, 3], dtype='uint8'))
img = img.filter(ImageFilter.BoxBlur(-2))
```



Discussion:
For me it crashes when the filter is used, not when it's created. I haven't looked into it any further than that.

Resolving patch:
diff --git a/src/PIL/ImageFilter.py b/src/PIL/ImageFilter.py
--- a/src/PIL/ImageFilter.py
+++ b/src/PIL/ImageFilter.py
@@ -183,6 +183,9 @@ class BoxBlur(MultibandFilter):
     name = "BoxBlur"
 
     def __init__(self, radius):
+        if radius < 0:
+            msg = "radius must be >= 0"
+            raise ValueError(msg)
         self.radius = radius
 
     def filter(self, image):


Test patch:
diff --git a/Tests/test_image_filter.py b/Tests/test_image_filter.py
--- a/Tests/test_image_filter.py
+++ b/Tests/test_image_filter.py
@@ -24,6 +24,7 @@
         ImageFilter.ModeFilter,
         ImageFilter.GaussianBlur,
         ImageFilter.GaussianBlur(5),
+        ImageFilter.BoxBlur(0),
         ImageFilter.BoxBlur(5),
         ImageFilter.UnsharpMask,
         ImageFilter.UnsharpMask(10),
@@ -173,3 +174,14 @@ def test_consistency_5x5(mode):
                 Image.merge(mode, source[: len(mode)]).filter(kernel),
                 Image.merge(mode, reference[: len(mode)]),
             )
+
+
+def test_invalid_box_blur_filter():
+    with pytest.raises(ValueError):
+        ImageFilter.BoxBlur(-2)
+
+    im = hopper()
+    box_blur_filter = ImageFilter.BoxBlur(2)
+    box_blur_filter.radius = -2
+    with pytest.raises(ValueError):
+        im.filter(box_blur_filter)
Repository: python-pillow/Pillow

Issue:
Image.register_open called multiple times
### What did you do?

Calling `Image.register_open` multiply times should not lead to growth of `Image.ID` list.

### What did you expect to happen?

After second call to `Image.register_open` `Image.ID` should not contain similar values.

### What are your OS, Python and Pillow versions?

* OS: not OS dependent
* Python: not python version dependent
* Pillow: 9.4.0


Maybe it is invalid usage, I know that applications should not call `Image.register_open`, but this very small problem present.

```python3
def register_open(id, factory, accept=None):
    """
    Register an image file plugin.  This function should not be used
    in application code.

    :param id: An image format identifier.
    :param factory: An image file factory method.
    :param accept: An optional function that can be used to quickly
       reject images having another format.
    """
    id = id.upper()
    ID.append(id)  # growth of the list here.
    OPEN[id] = factory, accept
```

Image.ID used only in a few places:

1. PIL.Image.open
```python3
    if formats is None:
        formats = ID
```
2. PIL.FitsStubImagePlugin
```python3
    # Override FitsImagePlugin with this handler
    # for backwards compatibility
    try:
        Image.ID.remove(FITSStubImageFile.format)
    except ValueError:
        pass

    Image.register_open(
        FITSStubImageFile.format, FITSStubImageFile, FitsImagePlugin._accept
    )
```
3. PIL.features
```python3
        for i in sorted(Image.ID):
            line = f"{i}"
            if i in Image.MIME:
                line = f"{line} {Image.MIME[i]}"
            print(line, file=out)
```

Probably in 1 and 3 places this can be replaced with `OPEN.keys()` that contain the same values, if I understand code correct, and in place with number 2 just remove `Image.ID.remove` lines.
These changes should not affect performance.



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
@@ -3406,7 +3406,8 @@ def register_open(id, factory, accept=None):
        reject images having another format.
     """
     id = id.upper()
-    ID.append(id)
+    if id not in ID:
+        ID.append(id)
     OPEN[id] = factory, accept
 
 


Test patch:
diff --git a/Tests/test_image.py b/Tests/test_image.py
--- a/Tests/test_image.py
+++ b/Tests/test_image.py
@@ -398,6 +398,17 @@ def test_alpha_inplace(self):
         with pytest.raises(ValueError):
             source.alpha_composite(over, (0, 0), (0, -1))
 
+    def test_register_open_duplicates(self):
+        # Arrange
+        factory, accept = Image.OPEN["JPEG"]
+        id_length = len(Image.ID)
+
+        # Act
+        Image.register_open("JPEG", factory, accept)
+
+        # Assert
+        assert len(Image.ID) == id_length
+
     def test_registered_extensions_uninitialized(self):
         # Arrange
         Image._initialized = 0
Repository: python-pillow/Pillow

Issue:
Cannot save PDF with mode RGBA
### What did you do?
```python
from PIL import Image
p=Image.open("e:/Downloads/pillow_putalpha_circle_blur.jp2")
p.save("e:/Downloads/pillow_putalpha_circle_blur.pdf")
````
test file
[pillow_putalpha_circle_blur.zip](https://github.com/python-pillow/Pillow/files/10562075/pillow_putalpha_circle_blur.zip)

### What did you expect to happen?
PDF with RGBA image encoded with JPXDecode filter

### What actually happened?
```
Traceback (most recent call last):
  File "<pyshell#268>", line 1, in <module>
    p.save("e:/Downloads/pillow_putalpha_circle_blur.pdf")
  File "C:\Python310\lib\site-packages\PIL\Image.py", line 2300, in save
    save_handler(self, fp, filename)
  File "C:\Python310\lib\site-packages\PIL\PdfImagePlugin.py", line 155, in _save
    raise ValueError(f"cannot save mode {im.mode}")
ValueError: cannot save mode RGBA
```

### What are your OS, Python and Pillow versions?
* OS: windows 11
* Python: 3.10.4
* Pillow: 9.1.1




Discussion:

Resolving patch:
diff --git a/src/PIL/PdfImagePlugin.py b/src/PIL/PdfImagePlugin.py
--- a/src/PIL/PdfImagePlugin.py
+++ b/src/PIL/PdfImagePlugin.py
@@ -173,6 +173,10 @@ def _save(im, fp, filename, save_all=False):
                 filter = "DCTDecode"
                 colorspace = PdfParser.PdfName("DeviceRGB")
                 procset = "ImageC"  # color images
+            elif im.mode == "RGBA":
+                filter = "JPXDecode"
+                colorspace = PdfParser.PdfName("DeviceRGB")
+                procset = "ImageC"  # color images
             elif im.mode == "CMYK":
                 filter = "DCTDecode"
                 colorspace = PdfParser.PdfName("DeviceCMYK")
@@ -199,6 +203,8 @@ def _save(im, fp, filename, save_all=False):
                 )
             elif filter == "DCTDecode":
                 Image.SAVE["JPEG"](im, op, filename)
+            elif filter == "JPXDecode":
+                Image.SAVE["JPEG2000"](im, op, filename)
             elif filter == "FlateDecode":
                 ImageFile._save(im, op, [("zip", (0, 0) + im.size, 0, im.mode)])
             elif filter == "RunLengthDecode":


Test patch:
diff --git a/Tests/test_file_pdf.py b/Tests/test_file_pdf.py
--- a/Tests/test_file_pdf.py
+++ b/Tests/test_file_pdf.py
@@ -8,7 +8,7 @@
 
 from PIL import Image, PdfParser, features
 
-from .helper import hopper, mark_if_feature_version
+from .helper import hopper, mark_if_feature_version, skip_unless_feature
 
 
 def helper_save_as_pdf(tmp_path, mode, **kwargs):
@@ -42,6 +42,11 @@ def test_save(tmp_path, mode):
     helper_save_as_pdf(tmp_path, mode)
 
 
+@skip_unless_feature("jpg_2000")
+def test_save_rgba(tmp_path):
+    helper_save_as_pdf(tmp_path, "RGBA")
+
+
 def test_monochrome(tmp_path):
     # Arrange
     mode = "1"
Repository: python-pillow/Pillow

Issue:
AttributeError: module 'PIL._imaging' has no attribute 'libtiff_support_custom_tags'
### What did you do?
```python
from io import BytesIO
from PIL import Image
img = Image.open("basi0g01.png")
img.save(BytesIO(), format="TIFF", compression="group4")
```
Image file `basi0g01.png`: ![basi0g01](https://user-images.githubusercontent.com/925560/225758528-ad3f53a9-cd49-434c-873a-93a7d32495ca.png)

### What did you expect to happen?
No error raised

### What actually happened?
```pytb
Traceback (most recent call last):
  File "./pil_bug.py", line 14, in <module>
    img.save(BytesIO(), format="TIFF", compression="group4")
  File "/home/lucas_cimon/.local/share/virtualenvs/fpdf2/lib/python3.8/site-packages/PIL/Image.py", line 2435, in save
    save_handler(self, fp, filename)
  File "/home/lucas_cimon/.local/share/virtualenvs/fpdf2/lib/python3.8/site-packages/PIL/TiffImagePlugin.py", line 1810, in _save
    if not Image.core.libtiff_support_custom_tags:
AttributeError: module 'PIL._imaging' has no attribute 'libtiff_support_custom_tags'
```

### What are your OS, Python and Pillow versions?

* OS: WSL (Ubuntu 20.04)
* Python: 3.8.10
* Pillow: https://github.com/python-pillow/Pillow/commit/64f29247c2a36c8c0d255c806132007913b11cf8

Note: I think this issue can be tagged with `TIFF` & `Bug`



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
@@ -1807,7 +1807,7 @@ def _save(im, fp, filename):
             # Custom items are supported for int, float, unicode, string and byte
             # values. Other types and tuples require a tagtype.
             if tag not in TiffTags.LIBTIFF_CORE:
-                if not Image.core.libtiff_support_custom_tags:
+                if not getattr(Image.core, "libtiff_support_custom_tags", False):
                     continue
 
                 if tag in ifd.tagtype:


Test patch: