Tag Archives: HTML

My HTMLEncode function in Java

Every now and then I have to work in an environment where imports of frameworks is prohibited and it in times like that that I had to create my own HTMLEncode function. Here is the result:

public static String HTMLEncode(String inputString) {
 
		// Check if string contains ANY special characters (<>"&)
		if(inputString.indexOf("<") != -1 || 
                   inputString.indexOf(">") != -1 || 
                   inputString.indexOf("\"") != -1 ||
                   inputString.indexOf("&") != -1) {
 
			char c;
			StringBuffer out = new StringBuffer();
			for(int i=0; i < inputString.length(); i++) {
 
			    c = inputString.charAt(i);
 
			    if(c=='"' || c=='<' || c=='>') {
			       out.append("&#"+(int)c+";");
			    }
			    else if(c == '&'){
                                // Is &-sign preceding an HTML entity?
			    	if(inputString.indexOf("&amp;", i) == i || 
			    		inputString.indexOf("& #38;", i) == i ||
		    			inputString.indexOf("& lt;", i)  == i || 
		    			inputString.indexOf("& #60;", i) == i ||
		    			inputString.indexOf("& gt;", i)  == i ||
		    			inputString.indexOf("& #62;", i) == i ||
		    			inputString.indexOf("& quot;", i)== i ||
		    			inputString.indexOf("& #34;", i) == i ){
 
			    		out.append(c);
 
			    	}
			    	else {
			    		out.append("&#"+(int)c+";");
			    	}
			    }
			    else {
			        out.append(c);
			    }		
			}			
			return out.toString();
		}
		else {
			return inputString;			
		}				
	}

NOTE! The spaces inside the strings on row 21 thru 27 are only there for displaying purposes. In real code these spaces should be removed

Embed pictures in HTML code with Base64 encoding

There are times when you do not want to reference a picture on a HTML page but you want the picture to be IN the HTML code. This can for example be if you are creating HTML to send in e-mails. Attaching a bunch of picture files does not always go well with mail software and spam filters.

The secret here is the “hidden” talents of the img tag which can read base64 encoded content. The syntax is:

<img src="data:{mime};base64,{data}" alt="My picture"/>

{Mime} is in ‘image/imagetype’ format (eg. ‘image/jpg’ or image/png) and {data} is the base64 encoded string
Example:

<img src="data:image/gif;base64, iVBORw0KGgoAAAANSUhEUgAAABYAAAAQCAIAAACdjxhxAAAC7mlDQ1BJQ0MgUHJvZmlsZQAAeAGF
VM9rE0EU/jZuqdAiCF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IxUjShAKCLMGR3BCkhZ6+hlNWoTjD6sKKkQqAEwMDSGRs5xiAAAAAElFTkSuQmCC" 
 alt="Flag of Sweden"/>

Here the mime is ‘image/gif’ since the picture data is from a gif file. You can also use image/png and image/jpg.
When running the code above through a browser we get:
Flag of Sweden

A small picture of the flag of Sweden. Not much, but base64 encoded pictures tend to be quite large in string form 🙂

Tested on OS X 10.6.8 and Chrome 16 Beta