Skip to content

Extract images

ozaru.extract_images returns every image of a PDF as an Image: the page it is on, its box, its size in pixels and the image itself, as a file you can save.

The examples use the sample brochure, a page with a photo and a logo.

Save every image

import ozaru

for image in ozaru.extract_images("brochure.pdf"):
    name = f"page{image.page}-{image.number}.{image.format}"
    image.save(name)
    print(f"{name}: {image.width} x {image.height} pixels, {image.x0:.0f} points from the left")

Output:

page1-1.jpeg: 240 x 160 pixels, 72 points from the left
page1-2.png: 32 x 32 pixels, 480 points from the left

format tells you what kind of file data holds, so you know which extension to give it:

format What it is
"jpeg" A JPEG photo, exactly as it is stored in the PDF, without losing quality. A photo with a transparency mask, or in CMYK, comes as "png" instead.
"jp2" A JPEG 2000 image, also as it is stored in the PDF.
"png" An image ozaru writes as a PNG file from its pixels, with its transparency as the alpha channel.

save(path) writes data to a file, and data gives you the same bytes, for example to send them somewhere without saving them first.

Where an image is

The box of an image, x0, y0, x1 and y1, is measured as the box of a word is: in points from the top left corner of the page, before the page is rotated. An image painted several times, like a logo on every page, comes once for each time it is painted.

width and height are the size of the image in pixels, which has nothing to do with the size it has on the page: a large photo can be painted small.

Scans, transparency and spot inks

Images with transparency, like a logo cut out of its background, come as PNG files with an alpha channel, so the background stays transparent. Black and white scans come as PNG files too, in fax encoding or in JBIG2, the compression of many scanners. So do images in spot inks, such as a Pantone color, /Separation and /DeviceN, with the colors the PDF gives for showing those inks on screen.

Images ozaru can't give yet

A damaged image comes with its page, box and size, but with format and data set to None, and save raises ValueError for it. So do the few images that use JBIG2 features ozaru doesn't read yet; see Limitations.

Next: count pages.