NAME
OpenOffice::OODoc::Image - Image manipulation methods
DESCRIPTION
The OpenOffice::OODoc::Image class is a derivative of OpenOffice::OODoc::XPath designed for the manipulation of graphics objects contained in documents. It mainly allows you to modify the size and position of an image and exchange its content outside the document.
This class should not be explicitly used in an ordinary application, because all its features are available in the OpenOffice::OODoc::Document class, in combination with other features. So, each time an application needs to get an image-focused access to a document, it should use the general odfDocument() constructor instead of the odfImage() one.
Practically, the present manual is provided to describe the image-container processing features of OpenOffice::OODoc::Document (knowing that these features are technically supported by the OpenOffice::OODoc::Image component of the API).
Knowing that an image is displayed or printed according to a style, the OpenOffice::OODoc::Image features should be used in conjunction with the OpenOffice::OODoc::Styles ones. The OpenOffice::OODoc::Document class allows the user to invoke text-, style- and image-focused methods from the same object.
All the methods described here can equally be used with images contained in style sheets (headers, footers) as with images contained in the body of a document. It can therefore be associated just as well with a "styles.xml" member as with a "content.xml" member of an OpenOffice.org file.
This class works with all types of document (text, presentation, etc.).
For all methods where the first argument is given below as "image", it is (unless otherwise stated) either the name of an image as it appears to the end user when editing its properties in OpenOffice.org or StarOffice or the image's element reference obtained previously by the program. All these methods fail and return a null value (or in some cases produce an error message) if the argument does not correspond to a known image contained in the document.
Note: This module is not an image-processing tool. It can insert or remove images, and control the way the images are displayed in the documents. But it can't process the images themselves.
Methods
Constructor : OpenOffice::OODoc::Image->new(<parameters>)
Short Form: odfImage(<parameters>)This constructor should not be explicitly used in ordinary applicationsknowing that all the features of the returned object are inherited byany Document object.See OpenOffice::OODoc::XPath->new for commun arguments.The XML member loaded by default is 'content.xml', but only member=> 'styles' is required if you want to work with page backgroundimages. Example:my $doc = odfImage(file => 'my_presentation.odp',part => 'styles.xml');Real applications should not expressly use this constructor,knowing that the compound OpenOffice::OODoc::Document (whoseusual constructor is ooDocument) inherits all the featuresof OpenOffice::OODoc::Image.
createImageElement(name [, options])
Creates an element which represents an image and inserts it into thedocument according to given parameters. The image element created isonly an anchor. It then needs to have a graphical content loadedinto it and, if needed, be given parameters using other methods.Example:$doc->createImageElement("Logo");inserts a default image element called "Logo".Normally, the image name is unique in an OpenOffice.org document butno checking of its uniqueness is performed here. Things you shouldknow, however, are:- if several images have the same name, one only of them can beretrieved and handled by methods which use the name to identifythem. It is almost impossible to know which of them it will be,without a thorough knowledge of the OpenOffice.org format andthe internal logic of OODoc.- if the document is subsequently read and saved byOpenOffice.org (which controls the uniqueness of image names),sequential numbers will be given to all but one of the repeatednames in order to make them unique.Attributes can be passed in pairs [parameter => value]. Such as:style => image style nameIt should be noted that an image should normally be associated witha graphic style. The presence of a style is not obligatory whencalling createImageElement (and this is not checked), but the imageshould preferably be actually linked to an existing style beforedisplaying or printing the document. See OpenOffice::OODoc::Stylesfor style creation or, better, OpenOffice::OODoc::Document for imagestyles.attachment => anchor elementindicates if the image is attached to a text element (for ex. aparagraph), and which one. This parameter must be an existingelement reference (obtained, for example, using getElement orselectElementxxx). It is useless if the image is linked to a page.The OASIS OpenDocument specification doesn't provide the list ofpossible attachments for an image, and OpenOffice.org make somedifferences in this area between the different document classes.For example, OOo Writer doesn't display images which are directlyattached to table cells, while OOo Calc does (in text documents,an image which appears in a table cell is attached to a paragraph,possibly empty, belonging to the cell; see the example below).page => anchor pageIf this parameter is used, it indicates that the image will beanchored to a page, and the given value is a page number. It doesnot matter if, when createImageElement is called, this number isbeyond the end of the document or not. If the content class of thedocument is "presentation" (Impress) or "drawing" (Draw), then thepage option is mandatory and must be either the visible name or theelement reference of an existing draw page. In a "text" content,all that matters is that the particular page exists when it is openedby OpenOffice.org and if this parameter is absent, the image isanchored to a paragraph.position => coordinatesThis parameter indicates the x,y coordinates of the image inrelation to its anchor point. By default and generally, if the pageparameter is given, the origin (0,0) is the top left corner of thephysical page. When attached to a text element, if there is no givenposition, the image is appended to the text.Coordinates go from left to right and top to bottom, howevereverything really depends on the image style. Coordinates should begiven here in the form of a string "x,y", and the default unit iscentimeters. You can choose millimeters instead by attaching theusual abbreviation, such as "12.5cm, 35mm" which is the same as"125mm, 3.5cm" or "12.5,3.5", etc. The point ("pt") unit is allowedas well.size => sizeThe image's size (width, height) is given here in the same syntax asfor position. Caution: if no size is given, you must not assume thatthe image will be spontaneously displayed in the document in aconvenient size. Remember that the "original" size of the image isnot automatically selected by default; the application must providea display size. If an image is to be displayed according to itsoriginal size which is not known in advance, you can get it using,for example, the imgsize() function of Image::Size (this functionreturns the size in points, so the "pt" unit must be expresslyselected unless you convert the size in centimeters).description => labelThis optional parameter gives the descriptive text (long label) forthe image as it will appear to the end user when editing the image'sproperties.link => linkThe link parameter contains a reference to the image's physicalcontent which can be inserted into an OpenOffice.org file (internallink) or a reference to an external file or even the URL of an imageaccessible using a communication protocol supported by theOpenOffice.org suite.Remember that, with OpenOffice.org, physical images are "referenced",and not "loaded" into XML elements. The reverse of course would notonly be against "good practice" but would result in outrageouslylarge documents. According to the OpenDocument specification, theconforming applications could embed base-64-encoded graphics in theXML elements, but this option is not used when you insert an imagein a document through the OOo GUI.If the target link is unavailable when the document is displayed,an error message is displayed in place of the image. (See imageLinkabout links.) This parameter is useless if import is given.Relative paths in the local filesystem are allowed, but should beused with care, due to differences between operating systems... andbetween editing applications (for example, in a Unix environment,OOo 2.x requires "../image.jpg" while OOo 1.x allows "image.jpg" fora link to an image file in the current directory).import => image fileThe presence of this parameter indicates that the image contentshould be imported from an external file and, implicitly, that theimage link (which it is useless to give here) points to the imageimported into the OpenOffice.org file. The import will only be madewhen all the updates are validated by a save(). See importImage()about importing images. An imported image is *not* embedded in theXML image element; it's always referred to through a link, and storedin a separate, non-XML member of the ODF archive. However, with the"import" option, the appropriate internal link is automaticallycreated and the new member, containing the image, is automaticallybuilt later, when the save() method is executed from the currentdocument (provided that the image file is available).For those who know the appropriate XML vocabulary, there are otherparameters you can pass. Parameters other than those described aboveare written to the image's XML element as is and without any checks.All of these attributes, and others, can be read or modified laterby other methods.We would discourage you from relying on the default choices in aserious application, but it is still a possibility. With noparameters (other than mandatory image name), the createImageElementmethod chooses its own often arbitrary course according to thefollowing circumstances:- if the OODoc::Image object is associated with a document body(document-content) then a new paragraph is created at the end ofthe document and the image is inserted into this paragraph(appears at the end of the text). Repeated image creationswithout parameters will therefore add images one after the otherat the end of the document.- if the OODoc::Image object is associated with a background(document-styles) then it tries to create a paragraph in thefirst available header and insert the image into it. If no pagestyle contains a header, the same is attempted in the firstavailable footer. If there is no footer either, the creationfails with the message "No valid attachment".This method otherwise tries to be "intelligent" whenever the set ofparameters is incomplete. If the results are useful, then the restis up to you...The method returns the new image element's reference (undef if itfails).The following example attaches an image to a paragraph, gives it asize, loads its content into it from an external file and attributesa style to it which has been defined elsewhere. You will note thatthis example combines an OODoc::Image method (createImageElement)with an OODoc::Text method (getParagraph). This means that, here,the $doc object is a OODoc::Document class. See alsocreateImageStyle in OODoc::Document.$doc->createImageElement("Landscape",description => "Kilimanjaro in winter",attachment => $doc->getParagraph(4),size => "5cm, 3.5cm",style => "gr1",import => "C:\Images\Landscape.jpg");The same image element could be inserted in a table cell. To doso, in a spreadsheet document, the "attachment" option could beset with a $doc->getCell($table, $row, $column) value. But thepresent version of OpenOffice.org doesn't allow direct cellattachments in text documents; the image element must be attachedto a paragraph which is in turn attached to the target cell. Soa possible approach consists of 1) issuing a setText($cell, "") inorder to ensure the target cell contains an empty text paragraphand 2) provide an "attachment" option set to$doc->getCellParagraph($cell) in order to anchor the image to thisparagraph.Remember: creating an image element will only make that image appearin the document if 1) the image has a valid link which points to avalid image, 2) the corresponding graphics file exists (loadedpossibly using importImage) in the archive if it is an internallink, and 3) the image has a style actually defined elsewhere(either pre-existing, created using the createStyle method ofOODoc::Styles, copied from another document using replicateElement,or coming from another source).
exportImage(image [, destination])
Exports the content of an image contained in a document if theOODoc::Image object was linked to a file when it was created (withfile or archive parameters passed to the new constructor).The first argument is either the name of the image (as it wouldappear to the end user in the image's properties in OpenOffice.org),or the image element's reference if the program already has it.The second optional argument is the destination file. Example:$doc->exportImage("Logo1", "C:\My Documents\logo.jpg");It is up to the application to choose an appropriate extension forthe exported file (.jpg, .gif, .png, etc.). You can easily find outwhich extension using the imageLink accessor.Without the second argument, the image file is created in thecurrent directory, and its name is the name of the image in thedocument, with an extension depending on the format (.jpg, .png,etc), according to the information stored in the document (butthe format is not checked). Be careful, the export fails unlesssuch a construct provides a valid file name for the operating system.If the image is unnamed in the document, exportImage() tries tobuild a path/name which replicates the internal path/name of theimage in the archive and to use it under the current directory(this path normally begins with "Pictures/").Caution: this method only exports what is exportable i.e. internalimages (physically contained in the file). It has no effect if usedwith an image inserted by an external link into the document.
exportImages([options])
Exports all or part of the images contained in a document.By default, and with no parameters, each internal image is exportedto a file whose access path is the same as it would be if usingexportImage. This behaviour can be changed by parameters passedin hash form (parameter => value).Possible parameters are as follows:selection => filtering of image names (regex)filter => filtering of image names (regex)name => filtering of image names (regex)target => path and/or basic filenamepath => path and/or basic filenamesuffix => extension to be given to filenamesextension => extension to be given to filenamesstart_count => begin count indicatorThe "filter", "selection" or "name" parameters allow you to exportonly those images whose names match the given regular expression.Such filtering works on the name as the document "knows" it, i.e. asit appears to the end user in the image's properties within thedocument. It is not a technical filter and does not allow, forexample, selection of images according to their file type.The "target" or "path" parameters allow you to choose the accesspath and basic filename for exported files (e.g."/usr/local/images/img"). If given, a sequential number willautomatically be added to the basic filename to identify each file.The "suffix" or "extension" parameters allow the application toforce a common extension for each file instead of leaving theextension as it existed in the archive (which normally identifies thephysical image type).By default, the sequential numbers given to filenames (between basicname and extension) are reset to zero each time exportImages iscalled. An application can however force the numbering to start at adifferent value using the "start_count" parameter.In a list context, this method returns a list of exported fileswhich the application can use later. In a scalar context, it returnsthe number of exported files.
getImageElementList()
Returns the list of all image elements in the active context. If thecurrent OODoc::Image object is associated with document-content,this will be the images contained in the body of the document. Ifassociated with document-styles, this will be the images linked toheaders and footers.
getImageElement(image)
getImageElement(element)
Returns the element which corresponds to the image whose name isgiven as an argument. This name is usually unique as OpenOffice.orgdoes not allow the user to give two files the same name in adocument. It is the name which appears in the "Options" tab whenediting the object's properties in OpenOffice.org Writer, or in the"Name object" dialog box when you right-click an image inOpenOffice.org Impress. Returns undef if the image is not found.Can also be used as a check method by specifying an element as theargument instead of a name. In this case, the given element issimply returned without modification if it is indeed an image orundef if not.Caution: images do not always have names. OpenOffice.org Writer givesdefault names to images (e.g. Image1, Image2, ...) if the user doesnot deliberately name them. This is not the case in Impress.
getInternalImagePath(image)
This method returns the given image's link (see definition of "link"in the section on imageLink), but only if it is an internal link ina form which is directly usable by a zip archive management tool(without the initial "#").
imageAttribute(image, attribute [, value])
Accessor which allows you to check or modify (even create) animage's XML attributes directly. The attribute is modified orcreated if a value is given as the third argument. If not, itreturns the current value of the attribute if found, or undef ifnot. The name and value of the attribute must be given according tothe OpenOffice.org vocabulary.This generic accessor remains invisible to most applications asspecialist accessors are available for the most useful attributes(e.g. imageLink, imageName, etc.).
imageDescription(image [, text])
Returns an image's description, or if the "text" argument is given,replaces it. This description corresponds to the optional text whichappears in the Options tab when editing the image's properties inOpenOffice.org. It is not used in Impress or Draw documents.
imageLink(image [, link])
Reads or modifies an image's link. A link is the address of the filewhich physically contains the image.If working with an image loaded into the document (often but notalways the case), the link is internal and the file is physicallystored in the zip archive containing the document. In this case, thelink is written as "#Pictures/xxxx". It corresponds to what the userwould see if opening the file using a zip archive tool instead ofopening it in OpenOffice.org.If working with an external image, the link is then the URL of theimage.The same method allows you to read and modify the link. If a secondargument is given, it cancels and replaces the existing link, orcreates a link if the image was still "empty".Example:$doc->imageLink("Logo", "http://www.mysite.com/logo.png");Caution: the actual physical existence of a valid image whichcorresponds to the link is not checked.
imageName(image [, name])
Reads an image's name, or if the second argument is given, replacesit.Returns undef if the first argument (name or reference) is not animage.
imagePosition(image [, x, y])
Allows you to read or modify the coordinates of an image in relationto its anchor point. Coordinates are returned in the form of a pairof values.Example:my ($x, $y) = $doc->imagePosition("Landscape");If the coordinate arguments are given, they replace the image's oldcoordinates.Caution: coordinates are not numeric values in the classic sense ofthe word. They are character strings starting with numeric valuesand ending with units of measure (normally "cm" or "mm"). If anapplication passes only numeric arguments without giving a unit ofmeasure, the default unit is assumed to be the centimetre.Example:$doc->imagePosition("Landscape", "2.5cm", "5.125cm");Normally, coordinates are measured from left to right and from topto bottom starting from the point of reference. The point ofreference is normally the top left corner of the page or paragraphto which it is anchored (depending on the type of anchorage). Allthis can depend on the page style.
imageSize(image [, height, width])
Allows you to read or modify the display size of an image. Returnsthe height and width as a pair of values. If height and widtharguments are provided, they replace the image's old size.Note that this method deals with the display size only, and ignoresthe original size of the image; in other words, it doesn't changeanything in the graphic object itself.Caution: it is up to the application to maintain the aspect ratio ofthe image if needed.See the "size" option about the createImageElement() method.See imagePosition() about measure formats.
imageStyle(image [, style])
Returns the name of the image's current style, or changes this styleif the second argument "style" is given. In the second case, thepresence or pertinence of the called style is not checked. This canotherwise be created or imported later.
importImage(image, filename)
Loads an image's content from an external file.Example:$doc->importImage("Image1", "C:\Images\Portrait.jpg");This import cancels and replaces any previous image content, if any.The first argument is either the image's name (as the user would seeit) or the image's corresponding element reference. In any case, theimage element must already exist, created if necessary usinginsertImageElement().The second argument is the full path of the image file to beimported and associated to the ODF image object. If this argument isomitted, importImage() assumes that the full path of the neededresource file is indicated by an external link already associatedwith the image object in the document (see imageLink).Obviously, the imported file should preferably be in a graphic formatsupported by most office software products, but this method actuallyallows you to import anything, including data which could not bedisplayed.Caution: this method does not carry out the import immediately anddoes not check for the presence of the file to be imported. It onlysends the request to the associated OODoc::File object (via itsraw_import method) which performs the operation at the next save()call. As a consequence, the image file is needed later, but itsavailability is not required by the importImage() method itself.
insertImageElement(name [, options])
See createImageElement.
isImage
Method added to OpenOffice::OODoc::Element class objects by theOODoc::Image package and is an element method rather than a documentmethod. Allows you to "ask" an element if it is an image.Example:print "This is an image" if $element->isImage;
removeImageDescription(image)
Deletes an image's optional image description.
selectImageElementByDescription(expression)
Returns the first (or only) image (if found) which has an imagedescription matching the provided regular expression.See also selectImageElementsByDescription().
selectImageElementByLink(link)
Allows you to select an image element by its link (as in imageLink)instead of by its name. The link can be an approximation andrepresented in this case by a regular expression.It should only be used if you are sure that the link is unique inthe document. This is not normally the case, as many images canshare the same content. Conversely, the returned element is thefirst image, in the physical XML order, which has the given link(and not necessarily in the logical order of the document).Returns undef if no image has the given link and therefore allowsyou to find out if a particular target (e.g. URL) is used in thedocument.Note: if an application needs to get a list of individual ormultiple images which share the same target, the easiest way is toloop through the list returned by getImageElementList() and perform animageLink() on each element.See also selectImageElementsByLink().
selectImageElementsByDescription(expression)
Returns a list of images whose image descriptions match the givenregular expression.
selectImageElementsByLink(expression)
Returns a list of images whose internal or external links match thegiven regular expression.Allows you, for example, to get a list of image elements which sharethe same physical image file or even those which use a particulartransport protocol to access these images.Example:my @webimages = $doc->selectImageElementsByLink("^http:");allows you to get a list of images referred to through an HTTP URL(i.e. which will not be visible if the user's machine is not connectedto the internet).
selectImageElementsByName(expression)
Returns a list of images whose names match the given regularexpression.
Properties
No variable is exported.There is a static class variable which contains the description of adefault image style (in hash form):%OpenOffice::OODoc::Image::DEFAULT_IMAGE_STYLEThis hash is not used directly by the module itself (which offers nostyles functions), but it is available to any application whichneeds to create image styles using either XPath base methods or theStyles module. Its structure is exactly the same as the parametershash expected by the createStyle method. By default, it isautomatically used by the createImageStyle method of the Documentmodule.
AUTHOR/COPYRIGHT
Developer/Maintainer: Jean-Marie Gouarne <http://jean.marie.gouarne.online.fr>
Contact: [email protected]
Copyright 2004-2009 by Genicorp, S.A. <http://www.genicorp.com>
Initial English version of the reference manual by Graeme A. Hunter ([email protected]).
License: GNU Lesser General Public License v2.1