Add Alt Text to Images in Java

To add alt text to images in Java, load an HTMLDocument, find its <img> elements, use hasAttribute("alt") to identify images with no alt attribute, add reviewed descriptions with setAttribute(), and save the updated HTML. Preserve intentional alt="" values used for decorative images.

Alternative text describes the purpose or content of an image when it cannot be seen. It supports screen-reader users, provides fallback information when an image does not load, and gives search systems textual context for meaningful images.

Aspose.HTML for Java provides DOM methods for finding image elements, inspecting their attributes, adding missing values, and saving the modified document. The API does not determine what an image means, so application code must obtain suitable descriptions from authors, a content system, reviewed metadata, or another trusted source.

Missing, Empty, and Descriptive Alt Text

An absent alt attribute and an empty alt attribute do not mean the same thing. Check the image purpose before changing either one.

HTMLMeaningRecommended action
<img src="chart.png">No text alternative was suppliedAdd meaningful alt text when the image conveys content or performs a function
<img src="divider.svg" alt="">The image is marked as decorativeKeep alt="" when assistive technologies should ignore the image
<img src="chart.png" alt="Quarterly revenue chart">A text alternative already existsPreserve it unless an editorial review finds it inaccurate

Images used as links or controls need text that communicates their purpose or action. Complex charts and diagrams can require a concise alt value plus a fuller description in the surrounding page content.

Find Images Without Alt Text in Java

The getElementsByTagName(“img”) method returns the image elements in document order. For each returned Element, hasAttribute(“alt”) distinguishes a missing attribute from an explicitly empty value.

The example uses alt-text-images.html. It contains two images without alt, one decorative image with alt="", and one image with an existing description.

Add Alt Text and Save the HTML File

The following Java example loads the sample file and uses a reviewed mapping between image paths and descriptions. It adds text with setAttribute() only when the alt attribute is absent and a description is available, then calls save() to write the updated HTML.

  1. Download alt-text-images.html to the application’s working directory.
  2. Load the file into an HTMLDocument.
  3. Prepare reviewed alternative text for the meaningful images.
  4. Retrieve all <img> elements with getElementsByTagName().
  5. Use hasAttribute("alt") to process only images whose alt attribute is missing.
  6. Add each available description with setAttribute("alt", description).
  7. Save the modified document as alt-text-images-updated.html.
 1import com.aspose.html.HTMLDocument;
 2import com.aspose.html.collections.HTMLCollection;
 3import com.aspose.html.dom.Element;
 4
 5import java.util.HashMap;
 6import java.util.Map;
 7
 8String inputPath = "alt-text-images.html";
 9String outputPath = "alt-text-images-updated.html";
10
11Map<String, String> descriptions = new HashMap<>();
12descriptions.put("photo1.png", "Wooden church and watchtower behind a log palisade");
13descriptions.put("photo2.png", "Snow-covered riverbank and city skyline reflected in calm water");
14
15HTMLDocument document = new HTMLDocument(inputPath);
16HTMLCollection images = document.getElementsByTagName("img");
17
18for (Element image : images) {
19    if (!image.hasAttribute("alt")) {
20        String source = image.getAttribute("src");
21        String description = descriptions.get(source);
22
23        if (description != null && !description.trim().isEmpty()) {
24            image.setAttribute("alt", description);
25            System.out.println("Alt text added for " + source);
26        }
27    }
28}
29
30document.save(outputPath);

The console reports the two updated images:

1Alt text added for photo1.png
2Alt text added for photo2.png

The saved document contains the following image elements:

1<img src="photo1.png" alt="Wooden church and watchtower behind a log palisade">
2<img src="photo2.png" alt="Snow-covered riverbank and city skyline reflected in calm water">
3<img src="gradient.svg" alt="">
4<img src="photo3.png" alt="Windmills in a green field beneath a cloudy sky">

The decorative image remains unchanged, and the existing windmill description is not overwritten.

Alt Text Best Practices

After updating a document, use the Screen Reader Accessibility workflow to check supported WCAG 2.0 rules related to text alternatives and inspect any remaining issues.

Common Alt Text Issues

IssueCause and fix
Decorative images receive unnecessary descriptionsThe code treats an empty alt value as missing. Check hasAttribute("alt") and preserve intentional alt="".
Existing descriptions are overwrittenUpdate only elements without the attribute, or run a separate editorial review before replacing existing values.
File names become poor alt textA file name rarely explains image purpose. Use reviewed descriptions from a content source or author.
Some images remain without alt textThe description mapping has no value for their src. Report these images for manual review rather than inventing text.
CSS background images are not foundgetElementsByTagName("img") finds HTML <img> elements, not images referenced by CSS background-image. Provide equivalent information in the page content when a background conveys meaning.

FAQ

What happens if an image already has alt text?

The example keeps it unchanged because hasAttribute("alt") returns true. Replace existing text only when an editorial or accessibility review determines that it is inaccurate.

Should code replace alt="" with a description?

Not automatically. An empty value commonly marks a decorative image that should be ignored by screen readers. Change it only when the image actually conveys information or performs a function.

Will adding alt text change the visual appearance of the page?

Normally, no. The attribute is primarily consumed by assistive technologies and can also provide fallback text when an image is unavailable.

Can I use the image file name as alt text?

A descriptive file name can be an input to an editorial workflow, but it should not be treated as a reliable final description. Alt text must reflect the image purpose in its page context.

Does the title attribute replace image alt text?

No. The title attribute is not a substitute for the required text alternative of a meaningful <img> element.

Can I add alt text to a CSS background image?

CSS background images do not have an alt attribute. Decorative backgrounds need no alternative text; if a background image conveys information, provide the equivalent information as accessible HTML content.

Related Articles