| 1 |
Integration with Pillow |
| 2 |
======================= |
| 3 |
|
| 4 |
https://pillow.readthedocs.io |
| 5 |
|
| 6 |
Creating an ImageSurface from a PIL Image: |
| 7 |
|
| 8 |
.. code:: python |
| 9 |
|
| 10 |
import cairo |
| 11 |
import PIL.Image as Image |
| 12 |
|
| 13 |
def from_pil(im: Image, alpha: float=1.0, format: cairo.Format=cairo.FORMAT_ARGB32) -> cairo.ImageSurface: |
| 14 |
""" |
| 15 |
:param im: Pillow Image |
| 16 |
:param alpha: 0..1 alpha to add to non-alpha images |
| 17 |
:param format: Pixel format for output surface |
| 18 |
""" |
| 19 |
assert format in ( |
| 20 |
cairo.FORMAT_RGB24, |
| 21 |
cairo.FORMAT_ARGB32, |
| 22 |
), f"Unsupported pixel format: {format}" |
| 23 |
if 'A' not in im.getbands(): |
| 24 |
im.putalpha(int(alpha * 256.)) |
| 25 |
arr = bytearray(im.tobytes('raw', 'BGRa')) |
| 26 |
surface = cairo.ImageSurface.create_for_data(arr, format, im.width, im.height) |
| 27 |
return surface |
| 28 |
|
| 29 |
|
| 30 |
filename = 'test.jpeg' |
| 31 |
|
| 32 |
# Open image to an ARGB32 ImageSurface |
| 33 |
im = Image.open(filename) |
| 34 |
surface1 = from_pil(im) |
| 35 |
|
| 36 |
# Open image to an RGB24 ImageSurface |
| 37 |
im = Image.open(filename) |
| 38 |
surface2 = from_pil(im, format=cairo.FORMAT_RGB24) |
| 39 |
|
| 40 |
# Open image to an ARGB32 ImageSurface, 50% opacity |
| 41 |
im = Image.open(filename) |
| 42 |
surface3 = from_pil(im, alpha=0.5, format=cairo.FORMAT_ARGB32) |
| 43 |
|
| 44 |
Converting an ImageSurface to a PIL Image: |
| 45 |
|
| 46 |
.. code:: python |
| 47 |
|
| 48 |
import cairo |
| 49 |
import PIL.Image as Image |
| 50 |
|
| 51 |
def to_pil(surface: cairo.ImageSurface) -> Image: |
| 52 |
format = surface.get_format() |
| 53 |
size = (surface.get_width(), surface.get_height()) |
| 54 |
stride = surface.get_stride() |
| 55 |
|
| 56 |
with surface.get_data() as memory: |
| 57 |
if format == cairo.Format.RGB24: |
| 58 |
return Image.frombuffer( |
| 59 |
"RGB", size, memory.tobytes(), |
| 60 |
'raw', "BGRX", stride) |
| 61 |
elif format == cairo.Format.ARGB32: |
| 62 |
return Image.frombuffer( |
| 63 |
"RGBA", size, memory.tobytes(), |
| 64 |
'raw', "BGRa", stride) |
| 65 |
else: |
| 66 |
raise NotImplementedError(repr(format)) |
| 67 |
|
| 68 |
# Create an image surface from a PNG file (or any other source) |
| 69 |
surface = cairo.ImageSurface.create_from_png("test.png") |
| 70 |
|
| 71 |
# Convert to a PIL Image |
| 72 |
im = to_pil(surface) |
| 73 |
|
| 74 |
# Use Pillow to store it as a JPEG |
| 75 |
im.save("result.jpg") |