0

I have an Android program in which I need to do the following:

I have a HTML string with the following contents:

<img src="image.png" />

Now I need to modify this tag as it is given here : embedd the base64 encoded imagedata direct into the -tag

I am able to achieve what the author says; I can convert the image to Base64.

My question here is I have the html string, I need to parse the string, read the image src value, convert image data to byte[], encode it & remodify the html string & then load it inside webview. ie; at the end my HTML content will have the following line :

<img src=\"data:image/jpeg;base64," + image64 + "\" />

What Java techniques can I use to read & modify the HTML string ? I need to do it in pure java rather than using available libraries. My original HTML file is a predefined one, so I cant create a new HTML but I need to modify the existing one. I tried using Html.fromHtml & override getDrawable(), but I dont know how to take this further to modify the html string.

4

1 回答 1

0

您应该使用 Pattern 和 Matcher 对象和正则表达式,例如:

public String renderHtml(String body) {
        Pattern pattern = Pattern.compile("[<](/)?img[^>]*[>]");
        Matcher matcher = pattern.matcher(body);
        StringBuilder builder = new StringBuilder();
        int i = 0;
        while (matcher.find()) {
            String replacement = getReplacement(matcher.group(0));
            builder.append(body.substring(i, matcher.start()));
            if (replacement == null)
                builder.append(matcher.group(0));
            else
                builder.append(replacement);
            i = matcher.end();
        }
        builder.append(body.substring(i, body.length()));
        return builder.toString();
    }
于 2013-09-12T14:18:01.460 回答