4

I am trying to paint a decoded jpeg to a Cairo surface... However I am kinda stuck and I have no idea how to move forward from

import cairo
import Image

path_to_jpeg = "/home/seif/Pictures/prw.jpg"
surface = cairo.PDFSurface ("out.pdf", 1000, 1000)
ctx = cairo.Context (surface)

image = cairo.ImageSurface(cairo.FORMAT_ARGB32, 1000, 1000)
dt = Image.open(path_to_jpeg)
dimage = dt.load()

Any help would be very appreciated...

smor
  • 161
  • 1
  • 8

2 Answers2

3

this should do the trick. You have to convert the image to a png first it seems to be the only format that you can create surfaces with. thats what a good chunk of the code below is doing. I recommend you look at this question which helped me a great deal in creating the code below.

import Image, StringIO
from cairo import PDFSurface, Context, ImageSurface

pdf = PDFSurface("out.pdf", 1000, 1000)
cr = Context(pdf)
im = Image.open("/home/seif/Pictures/prw.jpg")
buffer = StringIO.StringIO()
im.save(buffer, format="PNG")
buffer.seek(0)
cr.save()
cr.set_source_surface(ImageSurface.create_from_png(buffer))
cr.paint()
Community
  • 1
  • 1
Marwan Alsabbagh
  • 25,364
  • 9
  • 55
  • 65
2

If using cairocffi instead of pycairo (the API is compatible), the cairocffi.pixbuf module provides integration with GDK-PixBuf for loading all kinds of images formats into cairo.

https://cairocffi.readthedocs.io/en/stable/pixbuf.html

Example:

from cairocffi import ImageSurface, pixbuf

def get_image(image_data: bytes) -> ImageSurface:
    return pixbuf.decode_to_image_surface(image_data)[0]

def load_image(image_file_path: str) -> ImageSurface:
    with open(str(image_file_path), 'rb') as file:
        return get_image(file.read())
Mr. Clear
  • 471
  • 5
  • 13
Simon Sapin
  • 9,790
  • 3
  • 35
  • 44
  • Nice. But doesn't work with all files. For example: https://i.ytimg.com/vi/oVWEb-At8yc/hqdefault.jpg?sqp=-oaymwEZCNACELwBSFXyq4qpAwsIARUAAIhCGAFwAQ==&rs=AOn4CLCWOjDzCdKUUnl-hVwU64GIr1fs_A – Mr. Clear Jan 17 '20 at 11:23