home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeHTML & XHTML: The Definitive GuideSearch this book

5.2. Inserting Images in Your Documents

One of the most compelling features of HTML and XHTML is their ability to include images with your document text, either as an intrinsic component of the document (inline images), as separate documents specially selected for download via hyperlinks, or as a background for your document. When judiciously added to the body content, images -- static and animated icons, pictures, illustrations, drawings, and so on -- can make your documents more attractive, inviting, and professional looking, as well as informative and easy to browse. You may also specially enable an image so that it becomes a visual map of hyperlinks. When used to excess, however, images make your document cluttered, confusing, and inaccessible, as well as unnecessarily lengthening the time it takes for users to download and view your pages.

5.2.1. Understanding Image Formats

Neither HTML nor XHTML prescribe an official format for images. However, the popular browsers specifically accommodate certain image formats: GIF and JPEG, in particular (see following sections for explanations). Most other multimedia formats require special accessory applications that each browser owner must obtain, install, and successfully operate to view the special files. So it's not too surprising that GIF and JPEG are the de facto image standards on the Web.

Both image formats were already in widespread use before the Web came into being, so there's lots of supporting software out there to help you prepare your graphics for either format. However, each has its own advantages and drawbacks, including features that some browsers exploit for special display effects.

5.2.1.1. GIF

The Graphics Interchange Format (GIF) was first developed for image transfer among users of the CompuServe online service. The format has several features that make it popular for use in HTML and XHTML documents. Its encoding is cross-platform, so that with appropriate GIF decoding software (included with most browsers), the graphics you create and make into a GIF file on a Macintosh, for example, can be loaded into a Windows-based PC, decoded, and viewed without a lot of fuss. The second main feature is that GIF uses special compression technology that can significantly reduce the size of the image file for faster transfer over a network. GIF compression is "lossless," too; none of an image's original data is altered or deleted, so the uncompressed and decoded image exactly matches its original. And GIF images can be easily animated.

Even though GIF image files invariably have the .gif (or .GIF ) filename suffix, there actually are two GIF versions: the original GIF87 and an expanded GIF89a, which supports several new features, including transparent backgrounds, interlaced storage, and animation, that are popular with web authors (see section 5.2.1.2). The currently popular browsers support both GIF versions, which use the same encoding scheme that maps 8-bit pixel values to a color table, for a maximum of 256 colors per image. Most GIF images have even fewer colors; there are special tools to simplify the colors in more elaborate graphics. By simplifying the GIF images, you create a smaller color map and enhance pixel redundancy for better file compression and consequently faster downloading.

However, because of the limited number of colors, a GIF-encoded image is not always appropriate, particularly for photorealistic pictures (see JPEG discussion in Section 5.2.1.3, "JPEG"). GIFs make excellent icons, reduced color images, and drawings.

Because most graphical browsers explicitly support the GIF format, it is currently the most widely accepted image-encoding format on the Web. It is acceptable for both inline images and externally linked ones. When in doubt as to which image format to use, choose GIF.[30] It will work in almost any situation.

[30]We cannot resist the temptation to point out that choosy authors choose GIF.

5.2.1.2. Interlacing, transparency, and animation

GIF images can be made to perform three special tricks: interlacing, transparency, and animation. With interlacing, a GIF image seemingly materializes on the display, rather than progressively flowing onto it from top to bottom. Normally, a GIF encoded image is a sequence of pixel data, in order row-by-row, from top to bottom of the image. While the common GIF image renders onscreen like pulling down a window shade, interlaced GIFs open like a venetian blind. That's because interlacing sequences every fourth row of the image. Users get to see a full image -- top to bottom, albeit fuzzy -- in a quarter of the time it takes to download and display the remainder of the image. The resulting quarter-done image usually is clear enough so that users with slow network connections can evaluate whether to take the time to download the remainder of the image file.

Not all graphical browsers, although able to display an interlaced GIF, are actually able to display the materializing effects of interlacing. With those that do, users still can defeat the effect by choosing to delay image display until after download and decoding. Older browsers, on the other hand, always download and decode images before display and don't support the effect at all.

Another popular effect available with GIF images -- GIF89a-formatted images, actually -- is the ability to make a portion of them transparent so that what's underneath -- usually the browser window's background -- shows through. The transparent GIF image has one color in its color map designated as the background color. The browser simply ignores any pixel in the image that uses that background color, thereby letting the display window's background show through. By carefully cropping its dimensions and by using a solid, contiguous background color, a transparent image can be made to seamlessly meld into a page's surrounding content or float above it.

Transparent GIF images are great for any graphic you want to meld into the document and not stand out as a rectangular block. Transparent GIF logos are very popular, as are transparent icons and dingbats -- any graphic that should appear to have an arbitrary, natural shape. You may also insert a transparent image inline with conventional text to act as a special character glyph within conventional text.

The downside to transparency is that the GIF image will look lousy if you don't remove its border when it is included in a hyperlink anchor (<a> tag ), or is otherwise specially framed. And content flow happens around the image's rectangular dimensions, not adjacent to its apparent shape. That can lead to unnecessarily isolated images or odd-looking sections in your web pages.

The third unique trick available with GIF89a-formatted images is the ability to do simple frame-by-frame animation. Using special GIF animation software utilities, you may prepare a single GIF89a file to contain a series of GIF images. The browser displays each image in the file, one after the other, something like the page-flipping animation booklets we had (even drew!) as kids. Special control segments between each image in the GIF file let you set the number of times the browser runs through the complete sequence (looping), how long to pause between each image, whether the image space gets wiped to background before the browser displays the next image, and so on. By combining these control features with those normally available for GIF images, including individual color tables, transparency, and interlacing, you can create some very appealing and elaborate animations.[31]

[31]Songline Studios has published an entire book dedicated to GIF animation: GIF Animation Studio, by Richard Koman.

Simple GIF animation is powerful for one other important reason: you don't need to specially program your HTML documents to achieve animation. But there is one major downside that limits their use except for small, icon-sized, or thin bands of space in the browser window: GIF animation files get large fast, even if you are careful not to repeat static portions of the image in successive animation cells. And if you have several animations in one document, download delays may -- and usually will -- annoy the user. If there is any feature that deserves close scrutiny for excess, it's GIF animation.

Any and all GIF tricks -- interlacing, transparency, and animation -- don't just happen; you need special software to prepare the GIF file. Many image tools now save your creations or acquired images in GIF format, and most now let you enable transparency, as well as let you make interlaced GIF files. There also are a slew of shareware and freeware programs specialized for these tasks, as well as for creating GIF animation. Look into your favorite Internet software archives for GIF graphics and conversion tools and also see Chapter 17, "Tips, Tricks, and Hacks" for details on creating transparent images.

5.2.2. When to Use Images

Most pictures are worth a thousand words. But don't forget that no one pays attention to a blabbermouth. First and foremost, think of your document images as visual tools, not gratuitous trappings. They should support your text content and help readers navigate your documents. Use images to clarify, illustrate, or exemplify the contents. Content-supporting photographs, charts, graphs, maps, and drawings are all natural and appropriate candidates. Product photographs are essential components in online catalogs and shopping guides, for example. And link-enabled icons and dingbats, including animated images, can be effective visual guides to internal and external resources. If an image doesn't do any of these valuable services for your document, throw it out already!

One of the most important considerations when adding images to a document is the additional delay they add to the retrieval time for a document over the network, particularly for modem connections. While a common text document might run, at most, 10 or 15 thousand bytes, images can easily extend to hundreds of thousands of bytes each. And the total retrieval time for a document is not only equal to the sum of all its component parts, but also to compounded networking overhead delays.

Depending on the speed of the connection (bandwidth, usually expressed as bits or bytes per second) as well as network congestion that can delay connections, a single document containing one 100-kilobyte image may take anywhere from around 15 seconds through a 57.6 kilobit-per-second modem connection in the wee hours of the morning when most everyone else is asleep, to well over ten minutes with a 9600 bit-per-second modem at noon. You get the picture?

That said, of course, pictures and other multimedia are driving Internet providers to come up with faster, better, more robust ways to deliver Web content. Soon, 57.6 kilobit-per-second modem connections will go the way of the horse and carriage (as 9600 bit-per-second modems already have), to be replaced by technologies like cable modems and ADSL. Indeed, soon most connections will attain data rates approaching or exceeding what used to be available only to the biggest users (besides costing an arm and a leg), over a megabit per second.

Still, as the price lowers, use goes up, so there is the issue of congestion. If you are competing for access to an overburdened server, it doesn't matter how fast your connection may be.

5.2.3. When to Use Text

Text hasn't gone out of style. For some users, it is the only portion of your document they can access. We argue that, in most circumstances, your documents should be usable by readers who cannot view images or have disabled their automatic download in their browser to improve their connection. While the urge to add images to all of your documents may be strong, there are times when pure text documents make more sense.

Documents being converted to the Web from other formats rarely have embedded images. Reference materials and other serious content often is completely usable in a text-only form.

You should create text-only documents when access speed is critical. If you know that many users will be vying for your pages, you should accommodate them by avoiding the use of images within your documents. In some extreme cases, you might provide a home (leading) page that lets readers decide between duplicate collections of your work: one containing the images, and another stripped of them. (The popular browsers include special picture icons as place holders for yet-to-be downloaded images, which can trash and muddle your document's layout into an unreadable mess.)

Text is most appropriate -- supporting images only, without frills or nonessential graphics -- if your documents are to be readily searchable by any of the many web indexing services. Images are almost always ignored by these search engines. If the major content of your pages is provided with images, very little information about your documents will find its way into the online web directories.

5.2.4. Speeding Image Downloads

There are several ways to ameliorate the overhead and delays inherent with images, besides being very choosy about which to include in your documents:

Keep it simple

A full-screen, 24-bit color graphic, even when reduced in size by digital compression with one of the standard formats like GIF or JPEG, is still going to be a network bandwidth hog. Acquire and use the various image management tools to optimize image dimensions and number of colors into the fewest number of pixels. Simplify your drawings. Stay away from panoramic photographs. Avoid large empty backgrounds in your images, as well as gratuitous borders and other space-consuming elements. Also avoid dithering (blending two colors among adjacent pixels to achieve a third color); this technique can significantly reduce the compressibility of your images. Strive for large areas of uniform colors, which compress readily in both GIF and JPEG format.

Reuse images

This is particularly true for icons and GIF animations. Most browsers cache incoming document components in local storage for the very purpose of quick, network connection-less retrieval of data. For smaller GIF animation files, try to prepare each successive image to update only portions that change in the animation, rather than redraw the entire image (this speeds up the animation, too).

Divide up large documents

This is a general rule that includes images. Many small document segments, organized through hyperlinks (of course!) and effective tables of contents tend to be better accepted by users than a few large documents. In general, people would rather "flip" several pages than dawdle waiting for a large one to download. (It's related to the TV channel-surfing syndrome.) One accepted rule of thumb is to keep your documents under 50 kilobytes each, so even the slowest connections won't overly frustrate your readers.

Isolate necessarily large graphics

Provide a special link to large images, perhaps one that includes a thumbnail of the graphic, thereby letting readers decide if and when they want to spend the time downloading the full image. And since the downloaded image isn't mixed with other document components like inline images, it's much easier for the reader to identify and save the image on their system's local storage for later study. (For details on non-inline image downloads, see Section 5.6.2, "Referencing Audio, Video, and Images".)

Specify image dimensions

Finally, another way to improve performance is by including the image's rectangular height and width information in its tag. By supplying those dimensions, you eliminate the extra steps the extended browsers must take to download, examine, and calculate an image's space in the document. There is a downside to this approach, however, that we explore in Section 5.2.6.12, "Problems with height and width".

5.2.6. The <img> Tag

The <img> tag lets you reference and insert a graphic image into the current text flow of your document. There is no implied line or paragraph break before or after the <img> tag, so images can be truly "inline" with text and other content.

<img>

Function:

Inserts an image into a document

Attributes:

ALIGN

ONDBLCLICK

ALT

ONERROR

BORDER

ONKEYDOWN

CLASS

ONKEYPRESS

CONTROLS

ONKEYUP

DIR

ONLOAD

DYNSRC

ONMOUSEDOWN

HEIGHT

ONMOUSEMOVE

HSPACE

ONMOUSEOUT

ID

ONMOUSEOVER

ISMAP

ONMOUSEUP

LANG

SRC

LONGDESC

START

LOOP

STYLE

LOWSRC

TITLE

NAME

USEMAP

ONABORT

VSPACE

ONCLICK

WIDTH

End tag:

None in HTML; </img> or <img ... /> with XHTML

Contains:

Nothing

Used in:

text

The format of the image itself is not defined by the HTML or XHTML standard, although the popular graphical browsers support GIF and JPEG images. The standards don't specify or restrict the size or dimensions of the image, either. Images may have any number of colors, but how those colors are rendered is highly browser-dependent.

Image presentation in general is very browser-specific. Images may be ignored by nongraphical browsers. Browsers operating in a constrained environment may modify the image size or complexity. And users, particularly those with slow network connections, may choose to defer image loading altogether. Accordingly, you should make sure your documents make sense and are useful, even if the images are completely removed.

5.2.6.1. The src attribute

The src attribute for the <img> tag is required (unless you use dynsrc with Internet Explorer-based movies; see section 5.2.7.1). Its value is the image file's URL, either absolute or relative to the document referencing the image. To unclutter their document storage, authors typically collect image files into a separate folder they often name something like "pics" or "images." Section 6.2, "Referencing Documents: The URL"

For example, this HTML fragment places an image of a famous kumquat packing plant into the narrative text (see Figure 5-8):

Here we are, on day 17 of the tour, in front of the kumquat
packing plant:
<p>
<img src="pics/packing_plant.gif">
<p>
What an exciting moment, to see the boxes of fruit moving

In the example, the paragraph (<p>) tags surrounding the <img> tag cause the browser to render the image by itself with some vertical space after the preceding text and before the trailing text. Text may also abut the image, as we describe in Section 5.2.6.4, "The align attribute".

Figure 5-8

Figure 5-8. Image integrated with text

5.2.6.2. The lowsrc attribute

To the benefit of users, particularly those with slow Internet connections, Netscape provides the lowsrc companion to the src attribute in the <img> tag as a way to speed up document rendering. The lowsrc attribute's value, like src, is the URL of an image file that the browser loads and displays when it first encounters the <img> tag. When the document has been completely loaded and can be read by the user, Netscape retrieves the image specified by the src attribute.

The lowsrc image is a low-resolution, abbreviated version of the final src image that loads faster by comparison to quickly give the reader an idea of its content until the final, higher-resolution image eventually replaces it onscreen. But the lowsrc attribute can also be used for some very special effects.

Netscape uses the lowsrc image's dimensions to reserve space in the document for both the lowsrc and src images, unless you explicitly allocate that space with the height and width attributes described later in this chapter. Hence, if the dimensions of the image specified in the src attribute are different than those for the lowsrc image or your explicitly included height and width values, the src image will be reduced, enlarged, stretched, or compressed to fit in the allotted space. Moreover, the lowsrc and src images needn't be identical, so you might take advantage of the delayed rendering of the src image for simple animation.

The lowsrc attribute is for Netscape only. Other browsers ignore it and only load the image specified by the src attribute. Netscape won't load either image if the user chooses not to auto-load images. In that case, both images will load in order when the user clicks the images button or clicks the image icon placeholder. No browser loads the lowsrc image only; you must include a src image, otherwise nothing will appear except the missing image icon.

5.2.6.3. The alt and longdesc attributes

The alt attribute specifies alternative text the browser may show if image display is not possible or disabled by the user. It's an option, but one we highly recommend you exercise for most images in your document. This way, if the image is not available, the user still has some indication of what it is that's missing.

In addition, the latest browsers display the alternative description in a text box when users pass their mouse over the image. Accordingly, you might embed short, parenthetical information that pops up when users pass over a small, inline icon, such as shown in Figure 5-9.

Figure 5-9

Figure 5-9. Contemporary graphical browers display alt in a temporary pop-up window

The value for the alt attribute is a text string of up to 1024 characters if you include spaces or other punctuation. The string must be enclosed in quotation marks. The alternative text may contain entity references to special characters, but it may not contain any other sort of markup; in particular, no style tags are allowed.

Graphical browsers don't normally display the alt attribute if the image is available and the user has enabled picture downloading. Otherwise, they insert the alt attribute's text as a label next to an image placeholder icon. Well-chosen alt labels thereby additionally support those users with a graphical browser who have disabled their automatic image download because of a slow connection to the Web.

Nongraphical, text-only browsers like Lynx put the alt text directly into the content flow just like any other text element. So, when used effectively, the alt tag sometimes can transparently substitute for missing images. (Your text-only browser users will appreciate not being constantly reminded of their second-class web citizenship.) For example, consider using an asterisk as the alt attribute alternative to a special bullet icon:

<h3><img src="pics/fancy_bullet.gif" alt="*">Introduction</h3>

A graphical browser displays the bullet image, while in a nongraphical browser the alt asterisk takes the place of the missing bullet. Similarly, use alt text to replace special image bullets for list items. For example, the following code:

<ul>
  <li> Kumquat recipes <img src="pics/new.gif" alt="(New!)">
  <li> Annual harvest dates
</ul>

displays the new.gif image with graphical browsers, and the text "(New!)" with text-only browsers. The alt attribute uses even more complex text (see Figure 5-10):

Here we are, on day 17 of the tour, in front of the kumquat
packing plant:
<p>
<img src="pics/packing_plant.gif"
  alt="[Image of our tour group outside the main packing plant]">
<p>
What an exciting moment, to see the boxes of fruit moving
Figure 5-10

Figure 5-10. Text-only browsers like Lynx display an image's alt attribute text

The longdesc attribute is similar to the alt attribute, but allows for larger descriptions. The value of longdesc is the URL of a document containing a description of the image. If you have a description longer than 1024 characters, use the longdesc attribute to link to it. Neither HTML 4 nor XHTML specify what the content of the description must be, nor do any browsers currently implement longdesc; all bets are off when deciding how to create those long descriptions.

5.2.6.4. The align attribute

The standards don't define a default alignment for images with respect to other text and images in the same line of text: you can't always predict how the text and images will look.[32] HTML images normally appear in line with a single line of text. Common print media like magazines wrap text around images, with several lines next to and abutting the image, not just a single line.

[32]Most of the popular graphical browsers insert an image so its base aligns with the baseline of the text -- the same alignment specified by the attribute value of bottom. But document designers should assume that alignment varies between browsers and always include the desired type of image alignment.

Fortunately, document designers can exert some control over the alignment of images with the surrounding text through the align attribute for the <img> tag. The HTML and XHTML standards specify five image-alignment attribute values: left, right, top, middle, and bottom. The left and right values flow any subsequent text around the image, which is moved to the corresponding margin; the remaining three align the image vertically with respect to the surrounding text. Netscape adds four more vertical alignment attributes to that list: texttop, absmiddle, baseline, and absbottom, while Internet Explorer adds center.

The following list contains descriptions for the inline image alignments; see Figure 5-11 for examples.

Figure 5-11

Figure 5-11. Standard and browser-extended inline image alignments with text

top

The top of the image is aligned with the top edge of the tallest item in the current line of text. If there are no other images in the current line, the top of the image is aligned with the top of the text.

texttop

The align=texttop attribute and value tells Netscape to align the top of the image with the top of the tallest text item in the current line. It is different from the top option, which aligns the top of the image with the top of the tallest item, image or text, in the current line. If the line contains no other images that extend above the top of the text, texttop and top have the same effect.

middle

Netscape and Internet Explorer treat the middle image alignment value differently: Netscape aligns the middle of the image to the baseline of the text, regardless of other inline elements, such as another inline image (Figure 5-12). Internet Explorer aligns the middle of the image to the middle of the tallest item in the current line, text or image (Figure 5-13). Notice the alignments and differences in Figure 5-12 and Figure 5-13, particularly when only one image contains the align attribute. Both figures display the HTML fragment:

Line of text  
<img src="pics/horiz.gif" align=middle>
<img src="pics/vert.gif">
goes on ...
<br clear=left>
<p>
Line of text
<img src="pics/horiz.gif" align=middle>
<img src="pics/vert.gif" align=middle>
goes on ...

Also note that Internet Explorer Version 3 and later treats middle, absmiddle, and center the same, whereas earlier Internet Explorer versions and Netscape distinguish between middle and absmiddle alignments. (If you are confused as to exactly what each alignment value means, please raise your hand.)

Figure 5-12

Figure 5-12. Netscape aligns middle of image to baseline of text

Figure 5-13

Figure 5-13. Internet Explorer aligns middle of image to middle of tallest line element

absmiddle

If you set the align attribute of the <img> tag to absmiddle, the browser will fit the absolute middle of the image to the absolute middle of the current line. For Netscape and early versions of Internet Explorer, this is different from the common middle option, which aligns the middle of the image with the baseline of the current line of text (the bottom of the characters). Version 3 and later of Internet Explorer, on the other hand, treat absmiddle the same as middle and center.

center

The center image alignment value gets treated the same as absmiddle by both Internet Explorer and Netscape, but note that the browsers treat absmiddle and middle differently.

bottom and baseline (default)

With Netscape and early versions of Internet Explorer, the bottom and baseline image alignment values have the same effect as if you didn't include any alignment attribute at all: the browsers align the bottom of the image in the same horizontal plane as the baseline of the text. This is not to be confused with the absbottom, which takes into account letter "descenders" like the tail on the lowercase "y." Internet Explorer Version 3 and later, on the other hand, treat bottom the same as absbottom. (Did we see a hand up in the audience?)

absbottom

The align=absbottom attribute tells the browsers to align the bottom of the image with the true bottom of the current line of text. The true bottom is the lowest point in the text taking into account descenders, even if there are no descenders in the line. A descender is the tail on a "y," for example; the baseline of the text is the bottom of the "v" in the "y" character.

Use the top or middle alignment values for best integration of icons, dingbats, or other special inline effects with the text content. Otherwise, align=bottom (the default) usually gives the best appearance. When aligning one or more images on a single line, select the alignment that gives the best overall appearance to your document.

5.2.6.5. Wrapping text around images

The left and right image alignment values tell the browser to place an image against the left or right margin, respectively, of the current text flow. The browser then renders subsequent document content in the remaining portion of the flow adjacent to the image. The net result is that the document content following the image gets wrapped around the image.

<img src="pics/kumquat.gif" align=left>
The kumquat is the smallest of the citrus fruits, similar in appearance to a 
tiny orange. The similarity ends with its appearance, however. While oranges 
are generally sweet, kumquats are extremely bitter. Theirs is an acquired taste, to be sure.

Figure 5-14 shows text flow around a left-aligned image.

Figure 5-14

Figure 5-14. Text flow around a left-aligned image

You can place images against both margins simultaneously (Figure 5-15) and the text will run down the middle of the page between them:

<img src="pics/kumquat.gif" align=left>
<img src="pics/tree.gif" align=right>
The kumquat is the smallest of the citrus fruits, similar in appearance to a 
tiny orange. The similarity ends with its appearance, however. While oranges 
are generally sweet, kumquats are extremely bitter. Theirs is an acquired taste, to be sure.
Figure 5-15

Figure 5-15. Running text between left- and right-aligned images

While text is flowing around an image, the left (or right) margin of the page is temporarily redefined to be adjacent to the image as opposed to the edge of the page. Subsequent images with the same alignment will stack up against each other. The following source fragment achieves that staggered image effect:

<img src="pics/marcia.gif" align=left>
Marcia!
<br>
<img src="pics/jan.gif" align=left>
Jan!
<br>
<img src="pics/cindy.gif" align=left>
Cindy!

The results of this example are shown in Figure 5-16.

Figure 5-16

Figure 5-16. Three very lovely girls

When the text flows beyond the bottom of the image, the margin returns to its former position, typically at the edge of the browser window.

5.2.6.11. Resizing and flood-filling images

A hidden feature of the height and width attributes is that you don't need to specify the actual image dimensions; the attribute values can be larger or smaller than the actual size of the image. The browser automatically scales the image to fit the predefined space. This gives you a down-and-dirty way of creating thumbnail versions of large images and a way to enlarge very small pictures. Be careful, though: the browser still must download the entire file, no matter what its final rendered size is, and you will distort an image if you don't retain its original height versus width proportions.

Another trick with height and width provides an easy way to flood-fill areas of your page and can also improve document performance. Suppose you want to insert a colored bar across your document.[34]

[34]This is one way to create colored horizontal rules in Netscape 3 or earlier versions, which don't support the color attribute of the <hr> tag.

Rather than create an image to the full dimensions, create one that is just one pixel high and wide and set it to the desired color. Then use the height and width attributes to scale it to the larger size:

<img src="pics/one-pixel.gif" width=640 height=20>

The smaller image downloads much faster than a full-scale image, and the width and height attributes create the desired bar after the tiny image arrives at the browser (see Figure 5-18).

Figure 5-18

Figure 5-18. This bar was made from a one-pixel image

One last trick with the width attribute is to use a percentage value instead of an absolute pixel value. This causes the browser to scale the image to a percentage of the document window width. Thus, to create a colored bar 20 pixels high and the width of the window, you could use:

<img src="pics/one-pixel.gif" width="100%" height=20>

As the document window changes size, the image will change size as well.

If you provide a percentage width and omit the height, the browser will retain the image's aspect ratio as it grows and shrinks. This means that the height will always be in the correct proportion to the width and the image will display without distortion.

5.2.6.13. The hspace and vspace attributes

Graphical browsers usually don't give you much space between an image and the text around it. And unless you create a transparent image border that expands the space between them, the typical two-pixel buffer between an image and adjacent text is just too close for most designers' comfort. Add the image into a hyperlink, and the special colored border will negate any transparent buffer space you labored to create, as well as draw even more attention to how close the adjacent text butts up against the image.

The hspace and vspace attributes can give your images breathing room. With hspace, you specify the number of pixels of extra space to leave between the image and text on the left and right sides of the image; the vspace value is the number of pixels on the top and bottom:

<img src="pics/kumquat.gif" align=left>
The kumquat is the smallest of the citrus fruits, similar
in appearance to a tiny orange. The similarity ends with its
appearance, however. While oranges are generally sweet,
kumquats are extremely bitter. Theirs is an acquired taste,
to be sure. Most folks, at first taste, wonder how you could 
ever eat another, let alone enjoy it!
<p>
<img src="pics/kumquat.gif" align=left hspace=10 vspace=10>
The kumquat is the smallest of the citrus fruits, similar
in appearance to a tiny orange. The similarity ends with its
appearance, however. While oranges are generally sweet,
kumquats are extremely bitter. Theirs is an acquired taste,
to be sure. Most folks, at first taste, wonder how you could 
ever eat another, let alone enjoy it!

Figure 5-19 shows the difference between two wrapped images.

Figure 5-19

Figure 5-19. Improve image/text interfaces with vspace and hspace extensions

We're sure you'll agree that the additional space around the image makes the text easier to read and the overall page more attractive.

5.2.6.14. The ismap and usemap attributes

The ismap and usemap attributes for the <img> tag tell the browser that the image is a special mouse-selectable visual map of one or more hyperlinks, commonly known as an image map. The ismap style of image maps, known as a server-side image map, may be specified only within an <a> tag hyperlink. Section 6.3.1, "The <a> Tag"

For example:

<a href="/cgi-bin/images/map2"> 
  <img src="pics/map2.gif" ismap>
</a>

The browser automatically sends the x,y position of the mouse (relative to the upper-left corner of the image) to the server when the user clicks somewhere on the ismap image. Special server software (the /cgi-bin/images/map2 program in the example) may then use those coordinates to determine a response.

The usemap attribute provides a client-side image map mechanism that effectively eliminates server-side processing of the mouse coordinates and its incumbent network delays and problems. Using special <map> and <area> tags, HTML authors provide a map of coordinates for the hyperlink-sensitive regions in the usemap image along with related hyperlink URLs. The value of the usemap attribute is a URL that points to that special <map> section. The browser on the user's computer translates the coordinates of a click of the mouse on the image into some action, including loading and displaying another document. Section 6.5.3, "The <map> Tag" Section 6.5.4, "The <area> Tag"

For example, the following source specially encodes the 100 x 100-pixel map2.gif image into four segments, each of which, if clicked by the user, links to a different document. Notice we've included, validly, the ismap image map processing capability in the example <img> tag so that users of other, usemap-incapable browsers have access to the alternative, server-side mechanism to process the image map:

<a href="/cgi-bin/images/map2">
  <img src="pics/map2.gif" ismap usemap="#map2">
</a>
... 
<map name="map2">
  <area coords="0,0,49,49" href="link1.html"> 
  <area coords="50,0,99,49" href="link2.html"> 
  <area coords="0,50,49,99" href="link3.html"> 
  <area coords="50,50,99,99" href="link4.html"> 
</map>

Geographical maps make excellent ismap and usemap examples: browsing a nationwide company's pages, for instance, the users might click on their home towns on a map to get the addresses and phone numbers for nearby retail outlets. The advantage of the usemap client-side image map processing is that it does not require a server or special server software and so, unlike the ismap mechanism, can be used in non-web (networkless) environments, such as local files or CD-ROM.

Please read our more complete discussion of anchors and links, including image maps within links, in Section 6.5, "Mouse-Sensitive Images".

5.2.6.16. The name, onAbort, onError, onLoad and other event attributes

There are four <img> attributes currently supported by Netscape that enable you to use JavaScript to manipulate the image. The first is the name attribute. Now redundant with the standard id attribute,[35] name lets you label the image so that it can be referenced by a JavaScript applet.

[35]HTML Version 4.01 adopts the name attribute into the standard, even though only Netscape currently supports it with <img>.

For example:

<img src="pics/kumquat.gif" name="kumquat">

lets you later refer to that picture of a kumquat as simply "kumquat" in a JavaScript applet perhaps to erase or otherwise modify it. You cannot individually manipulate an image with JavaScript if it is not named or doesn't have an associated id.

The other three attributes let you provide some special JavaScript event handlers. The value of the attribute is a chunk of JavaScript code, enclosed in quotation marks; it may consist of one or more JavaScript expressions, separated by semicolons.

Netscape invokes the onAbort event handler if the user stops loading an image, usually by clicking the browser's "stop" button. You might, for instance, use an onAbort message to warn users if they stop loading some essential image, such as an image map (see Section 6.5, "Mouse-Sensitive Images"):

<img src="pics/kumquat.gif" usemap="#map1" 
onAbort="window.alert('Caution: This image contains important hyperlinks.  Please load the entire image.')">

The onError attribute is invoked if some error occurs during the loading of the image, but not for a missing image or one that the user chose to stop loading. Presumably, the applet could attempt to recover from the error or load a different image in its place.

Netscape executes the JavaScript code associated with the <img> tag's onLoad attribute right after the browser successfully loads and displays the image.

See Section 13.3.3, "Exploiting Multipart Documents" for more information about JavaScript and event handlers.

5.2.7. Video Extensions

The special controls, dynsrc, loop, and start attribute extensions for the <img> tag are unique to Internet Explorer and are not HTML 4 or XHTML standard attributes. They let you embed an inline movie into the body content, just like an image.

Equivalent behavior is available in Netscape via an extension program known as a plug-in. Plug-ins place an additional burden on the user, in that each user must find and install the appropriate plug-in before being able to view the inline video. The Internet Explorer <img> tag extensions, on the other hand, make video display an intrinsic part of the browser. Section 12.2, "Embedded Content"

However, the Internet Explorer movie extensions currently are very limited. They are not supported by any other browser and can be used only with Audio Video Interleave ( AVI) formatted movie files, since that's the player format built into Internet Explorer and enabled through Microsoft's Windows operating system software. Moreover, recent innovations in browser technology, objects, and applets in particular may make Internet Explorer's approach of extending the already overloaded <img> tag obsolete.

5.2.7.1. The dynsrc attribute

Use the dynsrc attribute extension in the <img> tag to reference an AVI movie for inline display by Internet Explorer. Its required value is the URL of the movie file enclosed in quotation marks. For example, this text displays the tag and attribute for an AVI movie file entitled intro.avi:

<img dynsrc="movies/intro.avi">

The browser sets aside a video viewport in the HTML display window and plays the movie, with audio if it's included in the clip and if your computer is able to play audio. Internet Explorer treats dynsrc movies similar to inline images: in line with current body content and according to the dimension of the video frame. And, like common images, the dynsrc referenced movie file gets displayed immediately after download from the server. You may change those defaults and add some user controls with other attributes, as described later.

Because all other browsers currently ignore the special Internet Explorer attributes for movies, they may become confused by an <img> tag that does not contain the otherwise required src attribute and an image URL. We recommend that you include the src attribute and a valid image file URL in all <img> tags, including those that reference a movie for Internet Explorer users. The other browsers display the still image in place of the movie; Internet Explorer does the reverse and plays the movie, but does not display the image. Note that the order of attributes does not matter. For example:

<img dynsrc="movies/intro.avi" src="pics/mvstill.gif">

Internet Explorer loads and plays the AVI movie intro.avi; other graphical browsers will load and display the mvstill.gif image instead.

5.2.7.3. The loop attribute

Internet Explorer normally plays a movie clip from beginning to end once after download. The loop attribute for the movie <img> tag lets you have the clip play repeatedly for an integer number of times set by the attribute's value, or forever if the value is infinite. The user may still cut the loop short by clicking on the movie image, by pressing the stop button, if given controls (see Section 5.2.7.2, "The controls attribute"), or by moving on to another document.

The following intro.avi movie clip will play from beginning to end, then restart at the beginning and play through to the end nine more times:

<img dynsrc="movies/intro.avi" loop=10 src="pics/mvstill.gif">

Whereas the following movie will play over and over again, incessantly:

<img dynsrc="movies/intro.avi" loop=infinite src="pics/mvstill.gif">

Looping movies aren't necessarily meant to annoy. Some special effects animations, for instance, are a sequence of repeated frames or segments. Rather than string the redundant segments into one, long movie that extends its download time, simply loop the single, compact segment.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.