Feb. 12, 2011, 2:13 p.m.
posted by pythonics
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 intrinsic components of the document (inline images), as separate documents specially selected for download via hyperlinks, or as background to your document or elements within the document. When judiciously added to the body content, imagesstatic and animated icons, pictures, illustrations, drawings, and so oncan 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, and they unnecessarily lengthen the time it takes for users to download and view your pages.
Understanding Image Formats
Neither HTML nor XHTML prescribes an official format for images. However, the popular browsers specifically accommodate certain image formats: GIF, PNG, and JPEG, in particular (see the 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, PNG, 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.
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. Also, 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 featuresincluding transparent backgrounds, interlaced storage, and animationthat are popular with web authors (see section 188.8.131.52). 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 the discussion in section 184.108.40.206). 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.[*] It will work in almost any situation.
Interlacing, transparency, and animation
You can make GIF images perform three special tricks: interlacing, transparency, and animation. With interlacing, a GIF image seemingly materializes on the display, instead of 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 the top to the 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 imagetop to bottom, albeit fuzzyin 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 imagesGIF89a-formatted images, that isis 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, you can make a transparent image seamlessly meld into or float above a page's surrounding content.
Transparent GIF images are great for any graphic that 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 dingbatsany 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 that contains 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 and perhaps 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.[*]
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 for anything other than small, icon-size, 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 mayand usually willannoy the user. If any feature deserves close scrutiny for excess, it's GIF animation.
Any and all GIF tricksinterlacing, transparency, and animationdon'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 and make interlaced GIF files. There also are a slew of shareware and freeware programs specialized for these tasks, as well as for creating GIF animations. Look into your favorite Internet software archives for GIF graphics and conversion tools, and see Chapter 17 for details on creating transparent images.
The Joint Photographic Experts Group (JPEG) is a standards body that developed what is now known as the JPEG image-encoding format. Like GIFs, JPEG images are platform independent and specially compressed for high-speed transfer via digital communication technologies. Unlike GIF, JPEG supports tens of thousands of colors for more detailed, photorealistic digital images. And JPEG uses special algorithms that yield much higher data-compression ratios. It is not uncommon, for example, for a 200 KB GIF image to be reduced to a 30 KB JPEG image. To achieve that amazing compression, JPEG does lose some image data. However, you can adjust the degree of "lossiness" with special JPEG tools so that although the uncompressed image may not exactly match the original, it will be close enough that most people cannot tell the difference.
Although JPEG is an excellent choice for photographs, it's not a particularly good choice for illustrations. The algorithms used for compressing and uncompressing the image leave noticeable artifacts when dealing with large areas of one color. Therefore, if you're trying to display a drawing, the GIF format may be preferable.
The JPEG format, usually designated by the .jpg (or .JPG) filename suffix, is nearly universally understood by today's graphical browsers. On rare occasions, you'll come across an older browser that cannot directly display JPEG images.
The Portable Network Graphics (PNG) technology originated to replace GIF, but not because GIF wasn't up to the job. Indeed, GIF was and probably still is the most widely implemented graphics format on the Internet. Instead, many Internet users got enraged when in 1993, after GIF had attained its popularity and widespread use, Unisys decided to enforce its patent and collect royalties on GIF's essential compression technology. That action ran against the widespread philosophy of free exchange and use enjoyed by the mostly academic community of Internet users, and prompted an informal Internet working group led by Thomas Boutell to develop the PNG alternative.
PNG's advantages over GIF and JPEG, besides providing a litigation-free alternative format, include a broader selection of color formats (24-bit true-color RGB, a grayscale and GIF-like 8-bit palette) and better lossless compression. PNG's unique and attractive features include alpha channels which let you specify many more than GIF's one layer of transparency (more than 65,000, actually) and can simulate 3D imagery, gamma correction which controls cross-platform image brightness for more vivid graphics, and two-dimensional interlacing which provides for a finer progressively developing image.
PNG does not support animation. Though you may hesitate to use PNG on that basis alone, we encourage you to try it out anyway, especially for high-color and high-quality images.
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 as 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,000 or 15,000 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 KB image may take less than a second through a cable modem connection in the wee hours of the morning, when most everyone else is asleep, to well over 10 minutes with a cell phone at noon. You get the picture?
With 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. Modem connections are quickly going the way of the horse and carriage, replaced by technologies like high-speed cable modems and the Asymmetric Digital Subscriber Line (ADSL).
Still, as the price lowers, use goes up, so there is the issue of congestion. And don't forget cell phone browsers and our Third World neighbors, where connections are spotty and slow. Besides, if you are competing for access to an overburdened server, it doesn't matter how fast your connection may be.
When to Use Text
Text hasn't gone out of style. For some users, it is the only accessible portion of your document. We argue that, in most circumstances, your documents should be usable by readers who cannot view images, or have disabled automatic download in their browsers to improve their connections. While the urge to add images to all of your documents may be strong, sometimes 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 are 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 placeholders for yet-to-be-downloaded images, which can trash and muddle your document's layout into an unreadable mess.)
Text is most appropriatesupporting images only, without frills and nonessential graphicsif your documents are to be readily searchable by any of the many web indexing services. These search engines almost always ignore images. If you provide the major content of your pages with images, very little information about your documents will find its way into the online web directories.
Speeding Image Downloads
There are several ways to reduce the overhead and delays inherent with images, besides being very choosy about which to include in your documents:
JPEG, PNG, or GIF?
You may choose to use only one type of image format in your HTML documents if your sources for images or your software tool set prefer one over the other format. All are nearly universally supported by today's browsers, so there shouldn't be any user-viewing problems.
Nevertheless, we recommend that you acquire the facilities to create and convert to at least the three formats we describe in this chapter to take advantage of their unique capabilities. For instance, use GIF's animation and PNG's transparency feature for icons and dingbats. Alternatively, use JPEG's deep compression, albeit at a loss of some integrity, for large and colorful images for faster downloading.
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 "in line" with text and other content.
The format of the image itself is not defined by the HTML or XHTML standard, although the popular graphical browsers support most common formats like GIF, PNG, 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 as allowed by their format, 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.
The HTML version of the <img> tag has no end tag. With XHTML, either use </img> immediately following the <img> tag and its attributes, or make the last character in the tag the end-tag slash mark: <img src="kumquat.gif" />, for example.
The src attribute
The src attribute for the <img> tag is required (unless you use dynsrc with Internet Explorer-based movies; see section 220.127.116.11). 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, which they often name something like "pics" or "images." [Referencing Documents: The URL, 6.2]
For example, this HTML fragment places an image of a famous kumquat packing plant into the narrative text (see Figure):
Image integrated with text
Here we are, on day 17 of the tour, in the kumquat packing plant: <p> <img src="pics/packing_plant.gif"> <p> What an exciting moment, to see the boxes of fruit piled high to
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 18.104.22.168.
The lowsrc attribute
To the benefit of users, particularly those with slow network connections, early versions of Netscape provided 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. Netscape before version 6 would load and display the lowsrc image when it first encountered the <img> tag. Then, when the document had been completely loaded and the user could read it, Netscape would retrieve the image specified by the src attribute.
No other browser besides Netscape versions 4 and earlier supports lowsrc. Netscape version 6 simply uses the dimensions of the lowsrc image to temporarily allocate display space for the image as it renders the document. The earlier versions of Netscape also used the lowsrc dimensions to resize the final image, which you could exploit for some special effects. This no longer works. Instead, we recommend that you eschew the Netscape extension and explicitly allocate image space with the height and width attributes described later in this chapter.
The alt and longdesc attributes
The alt attribute specifies alternative text the browser may show if image display is not possible or is disabled by the user. Especially favored by visually impaired users, the popular browsers also let us choose to display alt text along with the image. So although it's an option, it's 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's missing. And for users with certain disabilities, alt often is the only way they can appreciate your images.
In addition, Internet Explorer displays the alternative description in a text box when users pass the mouse over the image. Accordingly, you might embed short, parenthetical information that pops up when users pass over a small, inline icon, such as that shown in Figure.
Internet Explorer displays alt text in a temporary pop-up window
The value for the alt attribute is a text string of up to 1,024 characters, including spaces and punctuation. The string must be enclosed in quotation marks. The alt text may contain entity references to special characters, but it may not contain any other sort of markup; in particular, style tags aren't 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 graphical browsers who have disabled automatic image download because of a slow connection to the Web.
Nongraphical, text-only browsers such as the ancient 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; 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):
Text-only browsers such as Lynx display an image's alt attribute text
Here we are, on day 17 of the tour, in 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
The longdesc attribute is similar to the alt attribute but allows for longer descriptions. The value of longdesc is the URL of a document containing a description of the image. If you have a description longer than 1,024 characters, use the longdesc attribute to link to it. Neither HTML 4 nor XHTML specifies what the content of the description must be, and no browsers currently implement longdesc; all bets are off when deciding how to create those long descriptions.
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.[*] HTML images normally appear in line with a single line of text. Common print media such as magazines wrap text around images, with several lines next to and abutting the image, not just a single line.
Fortunately, document designers also 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 to the left or right of the image, which is moved to the corresponding margin (Figure). The remaining three align the image vertically with respect to the surrounding text.
Standard inline image alignments
All of the popular browsers, including Opera, Firefox, Netscape, and Internet Explorer, agree that align=bottom is the default vertical alignment, and similarly position images at the top of the uppermost character in the line of text, also shown in Figure.
The browsers disagree, however, on where to place an align=middle image with regard to text. As shown in Figure, Netscape and Opera place it in the apparent middle of the text. Internet Explorer and Firefox, on the other hand, place the image at the middle of the tallest element, not necessarily the tallest text (Figure).
Internet Explorer and Firefox align the middle of images to the middle of the tallest element, not to the middle of the text
The browsers also support, to varying degrees, five vertical image alignment extensionstexttop, center, absmiddle, baseline, and absbottom (if you are confused as to exactly what each alignment value means, please raise your hand):
Browsers take into account text descenders when aligning images with the align=absbottom attribute
Use the top or middle alignment value 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.
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 shows text flow around a left-aligned image.
Text flow around a left-aligned image
You can place images against both margins simultaneously (Figure), and the text will run down the middle of the page between them:
Running text between left- and right-aligned images
<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.
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.
Three very lovely girls from a very old sitcom
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.
Centering an image
Have you noticed that you can't horizontally center an image in the browser window with the align attribute? The middle and absmiddle values center the image vertically with the current line, but the image is horizontally justified depending on what content comes before it in the current flow and the dimensions of the browser window.
You can horizontally center an inline image in the browser window, but only if it's isolated from surrounding content, such as by paragraph, division, or line-break tags. Then, either use the <center> tag or use the align=center attribute or center-justified style in the paragraph or division tag to center the image. For example:
Kumquats are tasty treats <br> <center> <img src="pics/kumquat.gif"> </center> that everyone should strive to eat!
Kumquats are tasty treats <p align=center> <img src="pics/kumquat.gif"> </p> that everyone should strive to eat!
Align and <center> are deprecated
The HTML 4 and XHTML standards have deprecated the align attribute for all tags, including <img>, in deference to stylesheets. They've deprecated <center>, too. Nonetheless, the attribute and tag are very popular among HTML authors and remain well supported by the popular browsers. So, while we do expect that someday both align and <center> will disappear, it won't be anytime soon. Just don't say we didn't warn you.
What if you don't want to use align or <center>? Some authors and many of the WYSIWYG editors use HTML/XHTML tables to align content. That's one way, albeit involved (see Chapter 10). The World Wide Web Consortium (W3C) wants you to use styles. For example, use the margin-left style to indent the image from the left side of the display. You can read lots more about Cascading Style Sheets (CSS) in Chapter 8.
The border attribute
Browsers normally render images that also are hyperlinks (i.e., images included in an <a> tag) with a 2-pixel-wide colored border, indicating to the reader that he can select the image to visit the associated document. Use the border attribute and a pixel-width thickness value to remove (border=0) or widen that image border. Be aware that this attribute, too, is deprecated in HTML 4 and XHTML, in deference to stylesheets, but continues to be well supported by the popular browsers.
Figure shows you the thick and thin of image borders, as rendered by Internet Explorer from the following XHTML source:
The thick and thin of image borders
<a href="test.html"> <img src="pics/kumquat.gif" border="1" /> </a> <a href="test.html"> <img src="pics/kumquat.gif" border="2" /> </a> <a href="test.html"> <img src="pics/kumquat.gif" border="4" /> </a> <a href="test.html"> <img src="pics/kumquat.gif" border="8" /> </a>
Removing the image border
You can eliminate the border around an image hyperlink altogether with the border=0 attribute within the <img> tag. For some images, particularly image maps, the absence of a border can improve the appearance of your pages. Images that are clearly link buttons to other pages may also look best without borders.
Be careful, though, that by removing the border, you don't diminish your page's usability. No border means you've removed a common visual indicator of a link, making it more difficult for your readers to find the links on the page. Browsers will change the mouse cursor as the reader passes it over an image that is a hyperlink, but you should not assume they will, nor should you make readers test your borderless images to find hidden links.
We strongly recommend that with borderless images you use some additional way to let your readers know to click the images. Even including simple text instructions will go a long way toward making your pages more accessible to readers.
The height and width attributes
Ever watch the display of a page's contents shift around erratically while the document is loading? That happens because the browser readjusts the page layout to accommodate each loaded image. The browser determines the size of an imageand, hence, the rectangular space to reserve for it in the display windowby retrieving the image file and extracting its embedded height and width specifications. The browser then adjusts the page's display layout to insert that picture in the display.[*] This is not the most efficient way to render a document because the browser must sequentially examine each image file and calculate its screen space before rendering adjacent and subsequent document content. That can significantly increase the amount of time it takes to render the document and can disrupt reading by the user.
A more efficient way for authors to specify an image's dimensions is with the height and width <img> attributes. That way, the browser can reserve space before actually downloading an image, speeding document rendering and eliminating the content shifting. Both attributes require an integer value that indicates the image size in pixels; the order in which they appear in the <img> tag is not important.
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. Instead of creating an image to fill the full dimensions, create one that is just 1 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 one, and the width and height attributes have Firefox, for example, create the desired bright-red colored bar after the tiny image arrives at the browser (Figure).
This colored horizontal bar was made from a 1-pixel image
One last trick with the width attribute is to use a percentage value rather than 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.
Problems with height and width
Although the height and width attributes for the <img> tag can improve performance and let you perform neat tricks, there is a knotty downside to using them. The browser sets aside the specified rectangle of space to the prescribed dimensions in the display window, even if the user has turned off automatic download of images. What the user often is left with is a page full of semi-empty frames with meaningless picture-placeholder icons inside. The page looks terribly unfinished and is mostly useless. Without accompanying dimensions, on the other hand, the browser simply inserts a placeholder icon inline with the surrounding text, so at least there's something there to read in the display.
We don't have a solution for this dilemma, other than to insist that you use the alt attribute with some descriptive text so that users at least know what they are missing. We do recommend that you include these size attributes because we encourage any practice that improves display performance.
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 2-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 drawing 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 shows the difference between two wrapped images.
Improve image/text interfaces with vspace and hspace
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.
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. You can specify the ismap style of image maps only within an <a> tag hyperlink. [<a>, 6.3.1]
For example (notice the redundant attribute and value, as well as the trailing end-tag slash mark in the <img> tag, which are telltale signs of XHTML):
<a href="/cgi-bin/images/map2"> <img src="pics/map2.gif" ismap="ismap" /> </a>
The browser automatically sends the coordinates 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 ismap attribute is a server-side mechanism because it relies on the server for processing user input. 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 client computer translates the coordinates of a click of the mouse on the image into some action, including loading and displaying another document. [<map>, 6.5.3] [<area>, 6.5.4]
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 that 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 hometowns on a map to get the addresses and phone numbers for nearby retail outlets. The advantage of 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 nonweb (networkless) environments, such as local files and CD-ROMs.
Please read our more complete discussion of anchors and links, including image maps within links, in section 6.5.
The class, dir, event, id, lang, style, and title attributes
Several nearly universal attributes give you a common way to identify (title) and label (id) the image tag's contents for later reference or automated treatment, to change the contents' display characteristics (class, style), to reference the language (lang) used, and to specify the direction in which the text should flow (dir). And, of course, there are all the user events that may happen in and around the tagged contents that the browser senses and that you may react to via an on-event attribute and some programming. [Inline Styles: The style Attribute, 8.1.1] [Style Classes, 8.3]
The remaining attributes have questionable meaning in context with <img>. Granted, a few stylesheet options are available that may influence an image's display, and it's good to include a title (although alt is better). However, it's hard to imagine the influence that language (lang) or its presentation direction (dir) might have on an image. [The dir attribute, 22.214.171.124] [The lang attribute, 126.96.36.199]
The name, onAbort, onError, onLoad, and other event attributes
<img src="pics/kumquat.gif" name="kumquat">
The popular browsers invoke 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):
<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.
Combining <img> attributes
You may combine any of the various standard and extension attributes for images where and when they make sense. The order for inclusion of multiple attributes in the <img> tag is not important, either. Just be careful not to use redundant attributes, or you won't be able to predict the outcome.
Internet Explorer supports special video-related <img> attribute extensions that let you embed movies into your HTML documents: controls, dynsrc, loop, and start. These are not HTML 4 and are unlikely to become XHTML standard attributes. In fact, users have to specifically enable them with Internet Explorer's "Play video in web pages" Advanced Internet Options.
Equivalent behavior is available with all the popular browsers 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 software before being able to view the inline video. The Internet Explorer <img> tag extensions, on the other hand, made video display an intrinsic part of the browser. [Embedded Content, 12.2]
The dynsrc attribute
Use the dynsrc attribute extension in the <img> tag to reference an AVI, MPG or MPEG, MOV, WMV, or any popular movie format 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 titled intro.avi:
Internet Explorer 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.
The controls attribute
Normally, Internet Explorer plays a movie inside a framed viewport once, without any visible user controls. Although no longer supported in Internet Explorer version 5 or later, with older versions of the browser the controls attribute (no value) enabled users to restart, stop, and continue the movie by clicking inside that viewport with the mouse. If the movie clip includes a soundtrack, the earlier Internet Explorer provided an audio volume control as well. For example:
<img dynsrc="movies/intro.avi" controls src="pics/mvstill.gif">
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 the browser's Stop button 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. Instead of stringing the redundant segments into one long movie, which extends its download time, simply loop the single, compact segment.
The start attribute
Normally, an Internet Explorer movie clip starts playing as soon as it's downloaded. You can modify that behavior with the start attribute in the movie's <img> tag. By setting its value to mouseover, you delay playback until the user passes the mouse pointer over the movie viewport. The other valid start attribute value, fileopen, is the default: start playback just after download. It is included because both values may be combined in the start attribute, to cause the movie to play back automatically once, after download, and then whenever the user passes the mouse over its viewport. When combining the start attribute values, add a value-separating comma, with no intervening spaces, or else enclose them in quotes.
For example, our by-now-infamous intro.avi movie will play once when its host HTML document is loaded by the Internet Explorer user and again whenever he passes the mouse over the movie's viewport:
<img dynsrc="movies/intro.avi" start="fileopen,mouseover" src="pics/mvstill.gif">
Combining movie <img> attributes
Treat Internet Explorer inline movies as you would any image, mixing and matching the various movie-specific as well as the standard and extended <img> tag attributes and values supported by the browser. For example, you might align the movie (or its image alternative, if displayed by another browser) to the right of the browser window:
<img dynsrc="movies/intro.avi" src="pics/mvstill.gif" align=right>
Combining attributes to achieve a special effect is good. We also recommend that you combine attributes to give control to the user, when appropriate.
As we stated earlier in section 188.8.131.52, by combining attributes, you can also delay playback until the user passes the mouse over its viewport. Magically, the movie comes alive and plays continuously:
<img dynsrc="movies/magic.avi" start=mouseover loop=infinite src="pics/magic.gif">