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 above function to get emoji flags for United States, United Kingdom, France and Germany:

System.out.println(countryCodeToEmoji("US")); // πŸ‡ΊπŸ‡Έ
System.out.println(countryCodeToEmoji("UK")); // πŸ‡¬πŸ‡§
System.out.println(countryCodeToEmoji("FR")); // πŸ‡«πŸ‡·
System.out.println(countryCodeToEmoji("DE")); // πŸ‡©πŸ‡ͺ

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. β˜• Buy me a coffee (cost $3)


Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.