Techfee

About How to Embed Image Into One Single Html

| Comments

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
private static String embed(File htmlFile) {

      String final_return = "error";

      try {
          
          BufferedReader br = new BufferedReader(new FileReader(htmlFile));

          StringBuilder sb = new StringBuilder();

          String line = "";

          while ((line = br.readLine()) != null) {
              sb.append(line);
          }

          br.close();

          String htmlContent = sb.toString();

          org.jsoup.nodes.Document doc = Jsoup.parse(htmlContent);

          Elements images = doc.getElementsByTag("img");

          for (Element image : images) {

              String imgName = image.attr("src");

              // we surppose image files are in the same folder with the html file.
              File tempImageFile = new File(file.getParentFile().getAbsoluteFile()+"/"+ imgName);

              if (tempImageFile.exists() && imgName.trim() != "") {

                  String imageString = new String(

                  Base64.encodeBase64(FileUtils.readFileToByteArray(tempImageFile)));

                  image.attr("src", "data:image;base64," + imageString);

              }

              else {

                  // if the image file not exist, just put a empty string in it or leave it as it was
                  image.attr("src", "data:image;base64," + "");

              }

          }

          final_return = doc.toString();

      } catch (Exception e) {

          //do stuff...
      }

      return final_return;

  }

Comments