Add an Image to HTML in Java

To add an image to HTML in Java, create or load an HTMLDocument, create an <img> element with createElement("img"), set its src and alt attributes, append it to the required DOM element, and call save() to write the updated HTML.

Use an HTML <img> element when an image is part of the document content. Use the CSS background-image property when the image is decorative or belongs to the page layout. Aspose.HTML for Java provides DOM methods for both workflows.

This article shows how to add an image to a new HTML document, insert one into an existing file, and create a CSS background image.

Add an Image with the HTML img Element

An <img> element needs a src attribute that identifies the image resource. Meaningful images also need concise alt text. The optional width and height attributes reserve layout space, while CSS can control responsive rendering.

Add an Image to a New HTML Document

The following example creates an empty document, adds a responsive image to its <body>, and saves the result as add-image.html.

  1. Create an empty HTMLDocument.
  2. Create an <img> element with createElement().
  3. Set the image URL, alternative text, intrinsic dimensions, and responsive CSS with setAttribute().
  4. Add the image to the document body with appendChild().
  5. Save the HTML document.
 1import com.aspose.html.HTMLDocument;
 2import com.aspose.html.dom.Element;
 3
 4String outputPath = "add-image.html";
 5
 6HTMLDocument document = new HTMLDocument();
 7Element image = document.createElement("img");
 8
 9image.setAttribute("src", "https://docs.aspose.com/html/files/flower.svg");
10image.setAttribute("alt", "Stylized blue and pink flower");
11image.setAttribute("width", "300");
12image.setAttribute("height", "300");
13image.setAttribute("style", "max-width: 100%; height: auto;");
14
15document.getBody().appendChild(image);
16document.save(outputPath);

The saved document contains an <img> element in its body. The CSS lets the image shrink when its container is narrower than 300 pixels while preserving the aspect ratio. When the remote SVG is accessible, the save(String) overload also saves the linked resource in an adjacent resource folder.

Add an Image to an Existing HTML File

Use the same DOM operations to edit an existing page. The sample file image-insertion.html contains a <main> element with introductory content. The example loads that file, appends an image to <main>, and saves the changed document under a new name.

  1. Download image-insertion.html to the application’s working directory.
  2. Load the file into an HTMLDocument.
  3. Select the page’s <main> element.
  4. Create and configure an <img> element.
  5. Append the image to <main> and save image-insertion-updated.html.
 1import com.aspose.html.HTMLDocument;
 2import com.aspose.html.dom.Element;
 3
 4String inputPath = "image-insertion.html";
 5String outputPath = "image-insertion-updated.html";
 6
 7HTMLDocument document = new HTMLDocument(inputPath);
 8Element main = document.querySelector("main");
 9Element image = document.createElement("img");
10
11image.setAttribute("src", "https://docs.aspose.com/html/files/flower.svg");
12image.setAttribute("alt", "Stylized blue and pink flower");
13image.setAttribute("width", "240");
14image.setAttribute("height", "240");
15
16main.appendChild(image);
17document.save(outputPath);

The original file remains unchanged because the example saves the edited DOM to image-insertion-updated.html.

Add a Background Image with CSS

CSS background images do not create content nodes and do not support an alt attribute. Use them for decorative images or styling. When a background conveys information, provide the same information as accessible HTML text.

The following example adds a <style> element to the document <head>. Its CSS uses one image as a non-repeating background that covers the entire page.

  1. Load an existing HTML document.
  2. Create a <style> element and assign a background-image rule to it.
  3. Set background-repeat: no-repeat and background-size: cover.
  4. Find the document <head>, append the style element, and save background-image.html.
 1import com.aspose.html.HTMLDocument;
 2import com.aspose.html.dom.Element;
 3
 4String inputPath = "image-insertion.html";
 5String outputPath = "background-image.html";
 6
 7HTMLDocument document = new HTMLDocument(inputPath);
 8Element style = document.createElement("style");
 9
10style.setTextContent(
11        "body {"
12                + " background-image: url('https://docs.aspose.com/html/files/iceland-1.png');"
13                + " background-repeat: no-repeat;"
14                + " background-position: top right;"
15                + " background-size: cover;"
16                + "}"
17);
18
19Element head = document.querySelector("head");
20head.appendChild(style);
21document.save(outputPath);

The output uses one background image scaled to cover the page. The image keeps its aspect ratio, so cover can crop part of it when the page and image have different proportions.

Internal CSS keeps reusable rules in the document <head>. Inline CSS is convenient for styling one element but can become harder to maintain when repeated across a page.

Image Paths and Base URLs

The src attribute and CSS url() value can contain an absolute URL or a relative reference.

Choose img or background-image

RequirementUse
The image conveys content or performs a functionAn <img> element with appropriate alt text
The image is decorative or part of the layoutCSS background-image
The image should be discovered as document contentAn <img> element
The same decoration applies to several elementsA reusable CSS rule

Common Image Insertion Issues

IssueCause and fix
The image is brokenCheck the src value, base URL, file location, network access, and letter case in the path.
A relative image path resolves incorrectlyLoad the file from its actual location or provide the correct base URL when creating the document from HTML code.
The image distorts when resizedPreserve its aspect ratio. Set accurate width and height attributes and use CSS such as max-width: 100%; height: auto;.
A meaningful image has no accessible descriptionAdd an alt attribute that communicates the image’s purpose in context. Preserve alt="" for intentionally decorative <img> elements.
The background image repeatsAdd background-repeat: no-repeat, or deliberately configure repeat, repeat-x, or repeat-y.
Changes are not present in the source fileDOM changes remain in memory until save() is called. Confirm which output path the application saved.

FAQ

How do I insert an image into HTML in Java?

Create an element with document.createElement("img"), assign its src and alt attributes with setAttribute(), append it to the required parent node, and save the document.

Can the src attribute use a local image?

Yes. Use a relative reference such as images/photo.jpg or an appropriate file URL. Make sure the document base URL and saved folder structure allow the resource to be resolved.

Can I add an image from a URL?

Yes. Set src to an absolute HTTP or HTTPS URL. The save(String) overload can copy an accessible linked resource into an adjacent resource folder. Use HTMLSaveOptions when the application needs a different resource-handling policy.

How do I make an HTML image responsive?

Use CSS such as max-width: 100%; height: auto;. Accurate width and height attributes can still be retained to establish the aspect ratio and reserve layout space.

Can I embed an image as Base64 data?

Yes. Set src to a valid data URI such as data:image/png;base64,.... Embedding removes the separate image request but increases the size of the HTML document.

Should a CSS background image have alt text?

CSS backgrounds cannot have an alt attribute. Use them for decoration. If a background communicates important information, provide an accessible text equivalent in the HTML content.

Related Articles