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 (https://jsoup.org/). 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 org.jsoup.select.Elements;
import java.util.ArrayList;
public class JsoupImageSrcChange{
public static void main(String args[]){
String content="Hello I am attaching an image: 
";
System.out.println(changeImageNames(content));
}
public static String changeImageNames(String content) {
ArrayList 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
Hello I am attaching an image: 