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.

Java Technology – Hibernate [With Tutorial Link]

Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database. Hibernate solves object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions. The Hibernate 2.1 framework won a Jolt Award in 2005.

Hibernate is free as open source software that is distributed under the GNU Lesser General Public License.

Hibernate’s primary feature is mapping from Java classes to database tables (and from Java data types to SQL data types). Hibernate also provides data query and retrieval facilities. Hibernate generates the SQL calls and relieves the developer from manual result set handling and object conversion, keeping the application portable to all supported SQL databases, with database portability delivered at very little performance overhead.

Mapping:
Mapping Java classes to database table is accomplished through the configuration of an XML file or by using Java Annotation. When using an XML file, Hibernate can generate skeletal source code for the persistence classes. This is unnecessary when annotation is used. Hibernate can use the XML file or the annotation to maintain the database schema.

Facilities to arrange one-to-many and many-to-many relationships between classes are provided. In addition to managing association between objects, Hibernate can also manage reflexive associations where an object has a one-to-many relationship with other instances of its own type.

Hibernate supports the mapping of custom value types. This makes the following scenarios possible:

* Overriding the default SQL type that Hibernate chooses when mapping a column to a property
* Mapping Java Enum to columns as if they were regular properties
* Mapping a single property to multiple columns

Persistence:
Hibernate provides transparent persistence for Plain Old Java Objects (POJOs). The only strict requirement for a persistent class is a no-argument constructor, not compulsorily public. Proper behavior in some applications also requires special attention to the equals() and hashCode() methods.

Collections of data objects are typically stored in Java collection objects such as Set and List. Java Generics can be used in Java 5 and higher. Hibernate can be configured to lazy load associated collections. Lazy loading is the default as of Hibernate 3.

Related objects can be configured to cascade operations from one to the other. For example, a parent such as an Album object can be configured to cascade its save and/or delete operation to its child Track objects. This can reduce development time and ensure referential integrity. A dirty checking feature avoids unnecessary database write actions by performing SQL updates only on the modified fields of persistent objects.

Hibernate Query Language(HQL):
Hibernate provides a SQL inspired language called Hibernate Query Language (HQL) which allows SQL-like queries to be written against Hibernate’s data objects. Criteria Queries are provided as an object-oriented alternative to HQL.

Integration:
Hibernate can be used both in standalone Java applications and in Java EE applications using servlets or EJB session beans.

Entities and components:
In Hibernate jargon, an entity is a stand-alone object in Hibernate’s persistent mechanism which can be manipulated independently of other objects. In contrast, a component is subordinate to other entities and can be manipulated only with respect to other entities. For example, an Album object may represent an entity but the Tracks object associated with the Album objects would represent a component of the Album entity if it is assumed that Tracks can only be saved or retrieved from the database through the Album object.

History:
Hibernate was developed by a team of Java software developers around the world led by Gavin King. JBoss, Inc. (now part of Red Hat) later hired the lead Hibernate developers and worked with them in supporting Hibernate.

The current version of Hibernate is Version 3.x. This version has new features like a new Interceptor/Callback architecture, user defined filters, and JDK 5.0 Annotations (Java’s metadata feature). Hibernate 3 is now a certified implementation of the JPA 1.0 specification via a wrapper for the Core module which provides conformity with the JSR 220 JPA standard.

Application programming interface:

The Hibernate API is provided in the Java package org.hibernate.

org.hibernate.SessionFactory interface
References immutable and threadsafe object creating new Hibernate sessions. Hibernate-based applications are usually designed to make use only of a single instance of the class implementing this interface (often exposed using a singleton design pattern).

org.hibernate.Session interface
Represents a Hibernate session i.e. the main point of the manipulation performed on the database entities. The latter activities include (among the other things) managing the persistence state (transient, persisted, detached) of the objects, fetching the persisted ones from the database and the management of the transaction demarcation.

A session is intended to last as long as the logical transaction on the database. Due to the latter feature Session implementations are not expected to be threadsafe nor to be used by multiple clients.

(This article is taken from Wikipedia. All text is available under the terms of the GNU Free Documentation License)

———

A nicely written Java Hibernate Tutorial is available here.

Java Code Implementation Of Selection Sort

Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n^2) complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and also has performance advantages over more complicated algorithms in certain situations.

The algorithm works as follows:

1. Find the minimum value in the list
2. Swap it with the value in the first position
3. Repeat the steps above for the remainder of the list (starting at the second position and advancing each time)

Effectively, we divide the list into two parts: the sublist of items already sorted, which we build up from left to right and is found at the beginning, and the sublist of items remaining to be sorted, occupying the remainder of the array.

Selection sort can also be used on list structures that make add and remove efficient, such as a linked list. In this case it’s more common to remove the minimum element from the remainder of the list, and then insert it at the end of the values sorted so far.

Variants of Selection Sort:
Heapsort greatly improves the basic algorithm by using an implicit heap data structure to speed up finding and removing the lowest datum. If implemented correctly, the heap will allow finding the next lowest element in T(log n) time instead of T(n) for the inner loop in normal selection sort, reducing the total running time to T(n log n).

A bidirectional variant of selection sort, called cocktail sort, is an algorithm which finds both the minimum and maximum values in the list in every pass. This reduces the number of scans of the list by a factor of 2, eliminating some loop overhead but not actually decreasing the number of comparisons or swaps. Note, however, that cocktail sort more often refers to a bidirectional variant of bubble sort.

Selection sort can be implemented as a stable sort. If, rather than swapping in step 2, the minimum value is inserted into the first position (that is, all intervening items moved down), the algorithm is stable. However, this modification either requires a data structure that supports efficient insertions or deletions, such as a linked list, or it leads to performing T(n^2) writes. Either way, it eliminates the main advantage of insertion sort (which is always stable) over selection sort.

In the bingo sort variant, items are ordered by repeatedly looking through the remaining items to find the greatest value and moving all items with that value to their final location. Like counting sort, this is an efficient variant if there are many duplicate values. Indeed, selection sort does one pass through the remaining items for each item moved. Bingo sort does two passes for each value (not item): one pass to find the next biggest value, and one pass to move every item with that value to its final location. Thus if on average there are more than two items with each value, bingo sort may be faster.

(Source Of The Above Text: Wikipedia
Text is available under the Creative Commons Attribution/Share-Alike License)
———————————-

The following is my implementation of Selection Sort in Java.