Since Unicode characters are supported by all major browsers, you should consider using emojis instead of images for displaying countries' flags. Here is a little code snippet that converts country codes (ISO 3166-1 alpha-2) to corresponding emoji flags (Unicode regional indicator symbols) in Java:
public String countryCodeToEmoji(String code) {
// offset between uppercase ASCII and regional indicator symbols
int OFFSET = 127397;
// validate code
if(code == null || code.length() != 2) {
return "";
}
//fix for uk -> gb
if (code.equalsIgnoreCase("uk")) {
code = "gb";
}
// convert code to uppercase
code = code.toUpperCase();
StringBuilder emojiStr = new StringBuilder();
//loop all characters
for (int i = 0; i < code.length(); i++) {
emojiStr.appendCodePoint(code.charAt(i) + OFFSET);
}
// return emoji
return emojiStr.toString();
}
Let's use the above function to get emoji flags for the United States, United Kingdom, Germany, and Pakistan:
System.out.println(countryCodeToEmoji("US")); // 🇺🇸
System.out.println(countryCodeToEmoji("UK")); // 🇬🇧
System.out.println(countryCodeToEmoji("DE")); // 🇩🇪
System.out.println(countryCodeToEmoji("PK")); // 🇵🇰
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.