24 January 2012

CMYK images in PDFs

For the few of you out there that are parsing PDFs manually in python, JPEG images (including CMYK images) can be extracted with the following code fragment.
  # reader is a PDFReader object from pyPdf, value is the operand to a Do operator. 
from PIL import Image, ImageChops

  xobject = reader.getObject(value)
  if xobject['/Filter'] == '/DCTDecode':
    raw_data = xobject.getRawData()
    if xobject['/ColorSpace'] == '/DeviceRGB':
      _CreateFile('image/jpeg', filename, raw_data))
    else:
      f = cStringIO.StringIO(raw_data)
      of = cStringIO.StringIO()
      i = Image.open(f)
      if xobject['/ColorSpace'] == '/DeviceCMYK':
        i = ImageChops.invert(i)
      i.convert('RGB').save(of, 'JPEG')
      _CreateFile('image/jpeg', filename, of.getvalue())

The CMYK images I found in the PDFs needed to inverted. PIL versions before 1.1.7 would do that for you, but version 1.1.7 removed in the ImageChops.invert() call.

No comments:

Post a Comment