Image Extraction
Opening a presentation unpacks its images into temporary storage, and
slide.Images() reports the ones each slide references. What you get back is a
common.ImageRef describing the format and pixel size and holding a path into
that temporary storage, so writing an image to disk means copying it out through
tempstorage.Open rather than reading the path with os.Open.
| Call | Scope |
|---|---|
slide.Images() | Images this slide references, in relationship order. |
ppt.Images | Every image in the package, including layout and master images. |
Listing and saving
for si, slide := range ppt.Slides() {
for i, img := range slide.Images() {
out := fmt.Sprintf("slide%d_image%d.%s", si+1, i+1, img.Format())
in, err := tempstorage.Open(img.Path())
if err != nil {
return err
}
defer in.Close()
f, err := os.Create(out)
if err != nil {
return err
}
defer f.Close()
if _, err := io.Copy(f, in); err != nil {
return err
}
}
}Format() returns the name the Go image decoder gave the format, so png,
jpeg or gif, which is close enough to a file extension for the example to
use it as one. Note that a part stored as .jpg still reports jpeg, because
the format comes from decoding the bytes rather than from the part name. Map it
yourself if the extension has to match the original.
Size() returns an image.Point with the pixel dimensions read when the file
was opened. That is the image’s own resolution, not the size it is drawn at on
the slide, which comes from the picture shape’s extent.
Limitations
The temporary storage disappears when the presentation is closed. defer ppt.Close() removes the extracted files, so anything you want to keep has to be
copied before that runs. Holding an ImageRef past Close leaves you with a
path to nothing.
slide.Images() skips images that come only from the slide layout or the
master. A background or a logo that renders on every slide is not a slide image;
find it in ppt.Images instead, where every image in the package appears once.
Images used on several slides are stored once and reported once per slide that references them, so a run over every slide will write the same picture out more than once unless you deduplicate on the path.
Only direct image relationships of the slide are listed. A picture that belongs to another part the slide references, a chart or an embedded object, is a relationship of that part rather than of the slide, and does not appear.
Run the example
The example opens image.pptx, prints the number of images on each slide, and
writes each one out as slideN_imageM.<format> with its pixel dimensions.
git clone https://github.com/unidoc/unioffice-examples.git
cd unioffice-examples/presentation/image_extraction
go run main.goIf this is your first time using UniOffice, follow the getting started guide to create an API key and set up your development environment.