Merge pull request #7936 from adamjstewart/types/fromarray · python-pillow/Pillow@f8160b8

@@ -41,7 +41,7 @@

4141

from collections.abc import Callable, MutableMapping

4242

from enum import IntEnum

4343

from types import ModuleType

44-

from typing import IO, TYPE_CHECKING, Any, Literal, cast

44+

from typing import IO, TYPE_CHECKING, Any, Literal, Protocol, cast

45454646

# VERSION was removed in Pillow 6.0.0.

4747

# PILLOW_VERSION was removed in Pillow 9.0.0.

@@ -3018,7 +3018,7 @@ def frombytes(mode, size, data, decoder_name="raw", *args) -> Image:

30183018

return im

30193019302030203021-

def frombuffer(mode, size, data, decoder_name="raw", *args):

3021+

def frombuffer(mode, size, data, decoder_name="raw", *args) -> Image:

30223022

"""

30233023

Creates an image memory referencing pixel data in a byte buffer.

30243024

@@ -3074,7 +3074,17 @@ def frombuffer(mode, size, data, decoder_name="raw", *args):

30743074

return frombytes(mode, size, data, decoder_name, args)

30753075307630763077-

def fromarray(obj, mode=None):

3077+

class SupportsArrayInterface(Protocol):

3078+

"""

3079+

An object that has an ``__array_interface__`` dictionary.

3080+

"""

3081+3082+

@property

3083+

def __array_interface__(self) -> dict[str, Any]:

3084+

raise NotImplementedError()

3085+3086+3087+

def fromarray(obj: SupportsArrayInterface, mode: str | None = None) -> Image:

30783088

"""

30793089

Creates an image memory from an object exporting the array interface

30803090

(using the buffer protocol)::

@@ -3153,8 +3163,11 @@ def fromarray(obj, mode=None):

31533163

if strides is not None:

31543164

if hasattr(obj, "tobytes"):

31553165

obj = obj.tobytes()

3156-

else:

3166+

elif hasattr(obj, "tostring"):

31573167

obj = obj.tostring()

3168+

else:

3169+

msg = "'strides' requires either tobytes() or tostring()"

3170+

raise ValueError(msg)

3158317131593172

return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)

31603173