RGB To Hex and Hex To RGB Conversion Using Java and Regular Expressions

If you are working with some image processing in Java, you must have definitely known that the images are made up of tiny units called pixels whose color and transparency can be represented by numbers. In fact, the images are an array of Integers. Each integer is 32 bits. 32 bits is broken down into 8 bit blocks (thus 4 total blocks) and these four blocks of numbers represent Red, Green and Blue Color information and the Transparency. The image pixels can however be represented in the Hex Values as well.

The following program is nothing about image processing, but rather a standalone tool to convert the RGB values to Hex representations and vice versa.

package com.kushal.tools;

/**
 * @author Kushal Paudyal
 * Created On: 2011-05-17
 * Last Modified on 2012-01-27
 * 
 * RGBHexInterConverter.java
 * Utility to convert:
 * - Hex to RGB or
 * - RGB to HEX
 * 
 * Uses regular expressions to match the valid pattern of the input string.
 */
import java.awt.Color;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RGBHexInterConverter {
	static String commaSeparatedRGBPattern = "^(\d{3}),(\d{3}),(\d{3})$";
	static final int HEXLENGTH = 8;
	static final String hexaDecimalPattern = "^0x([\da-fA-F]{1,8})$";

	public static void main(String[] args) {
		/** Some sample RGB and HEX Values for Conversion */
		String RGBForHexConversion = "128,128,255";
		String hexForRGBConversion = "0x0077c8d2";

		/** Convert from RGB to HEX */
		covertRGBToHex(RGBForHexConversion);
		
		/** Convert from HEX to RGB */
		convertHexToRGB(hexForRGBConversion);
		
		/**Pass some invalid RGB value for Hex Conversion*/
		covertRGBToHex("3002,4001,5301");
		
		/**Pass some invalid HEX value for RGB Conversion*/
		convertHexToRGB("5xY077c8d2");	
		
	}

	/**
	 * @param hexForRGBConversion
	 *            - hex value string for conveting to RGB format. Valid format
	 *            is: 0xXXXXXXXX e.g. 0x0077c8d2
	 * @return comma separated rgb values in the format rrr,ggg, bbb e.g.
	 *         "119,200,210"
	 */
	private static String convertHexToRGB(String hexForRGBConversion) {
		System.out.println("...converting Hex to RGB");
		String rgbValue = "";
		Pattern hexPattern = Pattern.compile(hexaDecimalPattern);
		Matcher hexMatcher = hexPattern.matcher(hexForRGBConversion);

		if (hexMatcher.find()) {
			int hexInt = Integer.valueOf(hexForRGBConversion.substring(2), 16)
					.intValue();

			int r = (hexInt & 0xFF0000) >> 16;
			int g = (hexInt & 0xFF00) >> 8;
			int b = (hexInt & 0xFF);

			rgbValue = r + "," + g + "," + b;
			System.out.println("Hex Value: " + hexForRGBConversion
					+ "nEquivalent RGB Value: " + rgbValue);
		} else {
			System.out.println("Not a valid Hex String: " + hexForRGBConversion
					+ "n>>>Please check your input string.");
		}
		System.out.println();
		return rgbValue;

	}

	/**
	 * @param rgbForHexConversion
	 *           - comma separated rgb values in the format rrr,ggg, bbb e.g.
	 *            "119,200,210"
	 * @return equivalent hex in the format 0xXXXXXXXX e.g. 0x0077c8d2
	 * 
	 *        If the converted hex value is not 8 characters long, pads the
	 *         zeros in the front.
	 */
	private static String covertRGBToHex(String rgbForHexConversion) {
		System.out.println("...converting RGB to Hex");
		String hexValue = "";
		Pattern rgbPattern = Pattern.compile(commaSeparatedRGBPattern);
		Matcher rgbMatcher = rgbPattern.matcher(rgbForHexConversion);

		int red;
		int green;
		int blue;
		if (rgbMatcher.find()) {
			red = Integer.parseInt(rgbMatcher.group(1));
			green = Integer.parseInt(rgbMatcher.group(2));
			blue = Integer.parseInt(rgbMatcher.group(3));
			Color color = new Color(red, green, blue);
			hexValue = Integer.toHexString(color.getRGB() & 0x00ffffff);
			int numberOfZeroesNeededForPadding = HEXLENGTH - hexValue.length();
			String zeroPads = "";
			for (int i = 0; i < numberOfZeroesNeededForPadding; i++) {
				zeroPads += "0";
			}
			hexValue = "0x" + zeroPads + hexValue;
			System.out.println("RGB value: " + rgbForHexConversion
					+ "nEquivalent Hex Value: " + hexValue);
		} else {
			System.out.println("Not a valid RGB String: "+rgbForHexConversion
					+ "n>>>Please check your inut string.");
		}

		
		System.out.println();
		return hexValue;
	}
}

The following is the output of the above program:

...converting RGB to Hex
RGB value: 128,128,255
Equivalent Hex Value: 0x008080ff

...converting Hex to RGB
Hex Value: 0x0077c8d2
Equivalent RGB Value: 119,200,210

...converting RGB to Hex
Not a valid RGB String: 3002,4001,5301
>>>Please check your inut string.

...converting Hex to RGB
Not a valid Hex String: 5xY077c8d2
>>>Please check your input string.

[My Video Promotion]
  1. How to extract plain Text from HTML Website easily in Java
  2. How To Find What Java Version You Are Using?
  3. Computing the total, free and usable disk space easily using JDK 1.6
  4. Creating java.util.date and java.util.sql objects from Calendar object
  5. Bar Code Generation In Java Using iText API
  6. Simple Tag Generator In Java For Music Blogs
  7. Tutorial on Converting an List of Strings or Numbers to a CSV file with optional sorting
  8. Calling URL Browser From Java Application
  9. Java Reflection Tutorial – List Methods Of A Class
  10. Cleaning Punctuation And White Spaces From A String
  11. Java Tutorial – Using JCIFS to copy files to shared network drive using username and password
  12. Prime Number Finder In Java
  13. Utility Class For Getting SQL Connection and Closing It
  14. Java Design Pattern – Singleton Pattern
  15. Reading / Writing File in Java and String Manipulation
  16. How to capture a screenshot using Java and save it to a file?
  17. Calculating The Difference Between Two Dates In Terms of Months
  18. Getting The Name Of Currently Logged In User In The System
  19. How To Set And Get System Clipboard Contents In Java
  20. RGB To Hex and Hex To RGB Conversion Using Java and Regular Expressions
  21. Generating Nepali Unicode Sequence For Characters
  22. Java Tool To Compare Two Lists and Spit Out The Differences – Working Example
  23. Replacing non-ASCII characters using Java Regular Expressions
  24. Calculating Folder Size In Java
Tagged , , , , , , , , . Bookmark the permalink.

3 Responses to Calculating Folder Size In Java

  1. Pingback: Sanjaal.com » Latest Updates

  2. Jamie says:

    This approach uses less memory:

    public static class SizeCounter implements FileFilter
    {
    private long total = 0;
    public SizeCounter(){};
    public boolean accept(File pathname) {
    if ( pathname.isFile()) {
    total+=pathname.length();
    } else {
    pathname.listFiles(this);
    }
    return false;
    }
    public long getTotal()
    {
    return total;
    }
    }

    private static long getFileOrDirectorySize(File file) {
    SizeCounter counter = new SizeCounter();
    file.listFiles(counter);
    return counter.getTotal();
    }

  3. kushalzone says:

    Thank you Jamie for your optimized solution.

Leave a Reply to Jamie Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.