Search code examples
pythonjpegdecodecairo

paint decoded jpeg to cairo surface


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...


Solution

  • 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()