How to change src value from HTML img tag using Java


In this article, we will learn how to get All Images inside an HTML document String and also modify it using Java.

For this purpose we are going to use JSOUP – Java HTML Parser ( jsoup is a Java library for working with real-world HTML. It provides a very convenient API for fetching URLs and extracting and manipulating data, using the best of HTML5 DOM methods and CSS selectors.

Java Program for Changing Image File name inside HTML String:

import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import; import java.util.ArrayList; public class JsoupImageSrcChange{ public static void main(String args[]){ String content="<p>Hello I am attaching an image: <img src=\"file.jpg\" alt=\"file\"></p>"; System.out.println(changeImageNames(content)); } public static String changeImageNames(String content) { ArrayList<String> imgNames=new ArrayList<>(); Document doc = Jsoup.parse(content); Elements img = doc.getElementsByTag("img"); for (Element el : img) { String srcValue = el.attr("src"); System.out.println("Image Found!"); System.out.println("src attribute is : "+srcValue); srcValue=srcValue.replace("file","data"); System.out.println("changed src attribute is : "+srcValue); el.attr("src", srcValue); } return doc.body().html(); } }

Console Output:

Image Found! src attribute is : file.jpg changed src attribute is : data.jpg <p>Hello I am attaching an image: <img src="data.jpg" alt="file"></p>

Want to Clear Java Interview? Read Java Interview Notes prepared by Us

Are You Good enough in Java? Prove it!


Get Answers to your Programming Questions

Recommended Deals ends in

Quiz For You:

Search Tags

    Modify Img tag src value in Java String

    Get all image names in HTML document String using Java

    Java code to modify Image names or location at runtime in Java