Sunday, February 19, 2012

Image processing using SWT Image APIS

Eclipse SWT Image APIs provides great level of abstraction for all basic image processing operations like scaling , cropping etc.In this post I have provided code snippet to some of the most common image processing operations.
There are main two classes in SWT (org.eclipse.swt.graphics) Image API
  • org.eclipse.swt.graphics.Image
  • org.eclipse.swt.graphics.ImageData
Instances of Image class are graphics which have been prepared for display on a specific device. Instances of ImageData class are device-independent descriptions of images. They are typically used as an intermediate format between loading from or writing to streams and creating an Image.
Following code snippet shows creating Image reference as well as retrieving ImageData from image.
/* creating Image reference using image path */
Image imageRef = new Image(Display.getCurrent(), "image.jpg");
ImageData imageData = imageRef.getImageData();
//processing image data
//..
//creating image using image data
imageRef = new Image(Display.getCurrent(),imaimageDatage);

Following code snippet show scaling image

 
/**
 * An utility method to scale given image.
 * @param img
 * @param scale
 * @return
 */
public static Image scaleImage(Image img, int scale){
    Display display = Display.getCurrent();
    int width = img.getImageData().width;
    int height = img.getImageData().height;
    Image scaled = new Image(display,
            img.getImageData().scaledTo((int)(width*scale),(int)(height*scale)));
    return scaled;
}


Cropping image

private static Image cropImage(Image sourceImage, int x, int y, int height, int width){
    Image croppedImage = new Image(Display.getCurrent(), width, height);
    GC gc = new GC(sourceImage);
    gc.copyArea(croppedImage, x, y);
    gc.dispose();
    return croppedImage;
}

ImageData allows to make background of an image transparent. This can be achieved by marking particular color pixel as transparent. Every image’s color information is represented by color palette. Every image has color palette based on color depth information of image, for example 8 bit depth image will have 2^8 (256) palette. Following code snippet show  making image background as transparent .
//making white background transparent
Image transparentImage = transparentImage(sourceImage, new RGB(255,255,255));
 
/**
*
*/
private static Image transparentImage(Image sourceImage, RGB backgroundColor){
    ImageData data = sourceImage.getImageData();
    if(backgroundColor == null){
        backgroundColor = new RGB(192,192,192); //Grey
    }
    data.transparentPixel = data.palette.getPixel(new RGB(192,192,192));
    return new Image(Display.getCurrent(),data);
}

Saturday, December 24, 2011

Using EnumSet by Example

In previous example I have explained using enum using color constants. Java util collection has provides EnumSet, it is a specialized Set implementation for use with enum types. In this post I have explained usage of EnumSet using an example.
A text can have multiple attributes like bold, italic, underlined etc. Given a text can have these properties, defined a sample Text class with bit fields as text properties
public class Text {
    //defining Text properties using int
    public static final  int BOLD = 1<<0;
    public static final  int ITALIC = 1<<1;
    public static final int UNDERLINED = 1<<2;
    
    private int style;
    public Text(int style){
        this.style = style;
    }
    
    public boolean isBold(){
        return (BOLD&style)==BOLD;
    }
    
    public boolean isItalic(){
        return (ITALIC&style)==ITALIC;
    }
    
    public boolean isUnderlined(){
        return (UNDERLINED&style)==UNDERLINED;
    }
    
    public static void main(String[] args) {
        Text t = new Text(BOLD|ITALIC);
        System.out.println("isBold = " + t.isBold());
        System.out.println("is Italic = "+ t.isItalic());
        System.out.println("is Underlined = " + t.isUnderlined());
        
    }
 
}

Above class uses bit operation to apply properties. Usage of the Text class is shown in main() method.Text’s constructor accepts styles and based on bid operations the properties styles are decided. Output of above program

isBold = true
is Italic = true
is Underlined = false


As above program using bit field, it has all disadvantages of int enum constants as discussed in previous post. Above implementation is prone to error as well as not type safe.
Above functionalities can be achieved by EnumSet, EnumSet provides efficient way of representing set of values from same enum type.

public class Text {
    public static enum Style {
        BOLD, ITALIC, UNDERLINED
    }
    
    Set<Style> styles = null;
    public Text(Set<Style> styles){
        this.styles = styles;
    }
    
    public boolean isBold(){
        return styles.contains(Style.BOLD);
    }
    
    public boolean isItalic(){
        return styles.contains(Style.ITALIC);
    }
    
    public boolean isUnderlined(){
        return styles.contains(Style.UNDERLINED);
    }
    
    public static void main(String[] args) {
        Text t = new Text(EnumSet.of(Style.BOLD,Style.UNDERLINED));
        System.out.println("isBold = " + t.isBold());
        System.out.println("is Italic = "+ t.isItalic());
        System.out.println("is Underlined = " + t.isUnderlined());
        
    }
}

Unlike previous implementation, we have defined enum for styles constants and Text’s constructor accept Set<Style> as parameter.EnumSet.of(…) returns of instance of EnumSet which acts as Set of constants of Style enum. This instance is equivalent to any other Collection classes and supports all corresponding functionalities like contains(). This approach provides additional benefits compared to previous implantations.
  • Type Safe
  • All benefits of Collection framework
  • Error safe

Java Enum in details

Java 5 has brought linguistic support for enumerated types. An enum type is a type whose fields consist of a fixed set of constants. The enum provides following features
  • Typesafe
  • Namespace
  • Printable constants values
Typical and often enum is being used to replace int constants. For example constants for color codes
public static final int RED = 0;
public static final int GREEN = 1;
public static final int BLUE = 3;
public static final int WHITE =4;
public static final int BLACK = 6;
 

This code can be replaced by following enum
public enum StandardColor {
    RED,GREEN,BLUE,WHITE,BLACK
}

Given the above enum declared, we can use the same to communicate the color preferences. For example we have Window class and it supports setting background color using setBackgroundColor(StandardColor color). One can call setBackgroundColor method on Window's instance to set background color, as shown in code below
public class Window{
    //..
    public setBackgroundColor(StandardColor color){
        if(color == StandardColor.Black){
            setBackgroundColor(#000000);
        } else if(color == StandardColor.WHITE){
            setBackgroundColor(#FFFFFF);
        }
        //..
    }
}


Windows myWindow = new Window();
myWindow.setBackgroundColor(StandardColor.BLACK);

Everything will go smooth till you have same understanding between StandardColor enum elements declaration and its implementers. Now consider the case you have to declare another color entry called “MY_COLOR” and corresponding html code will be#0000A0”. To let the corresponding html code we may document in comment.
enum StandardColor {
    BLACK,WHITE,RED,GREEN,BLUE,
    /**
     * HTML Code #0000A0
     */
    MY_COLOR
}

Addition to that we need to modify setBackgroundColor() method
public setBackgroundColor(StandardColor color){
    if(color == StandardColor.Black){
        setBackgroundColor(#000000);
    } else if(color == StandardColor.WHITE){
        setBackgroundColor(#FFFFFF);
    } else if(color == StandardColor.MY_COLOR){
        setBackgroundColor(#0000A0);
    }
    //..
}

Here is the problems, it you modify the color code, then all corresponding needs to be changed.
Java programming language enum types are much more powerful, the enum class body can include methods and other fields.Each enum constants can be declared with values. These values are passed to the constructor when constants are created. Enum StandardColor constants with RGB values to represent its actual value will make it self explanatory.
enum StandardColor {
    RED(255,0,0),
    GREEN(0,255,0),
    BLUE(0,0,255),
    WHITE(255,255,255), 
    BLACK(0,0,0) ;
    final int r,g,b;
    private StandardColor(int rParam, int gParam, int bPram){
        r = rParam;
        g = gParam;
        b = bPram;
    }
    
    public String getHexValue(){
        return "#"+ Integer.toHexString(r)+Integer.toHexString(g)+Integer.toHexString(b);
    }
    
    private String intToHex(int i){
        return Integer.toHexString(i);
    }
}
Here enum StandardColor constants accept three integer representing red, green and blue values while declaring it. As seen in code above , it has private constructor with three integers and a public method getHexValue() to get html value of color. Now the Windows.setBackgroundColor(StandardColor) method will be much more simpler that previous version.
public setBackgroundColor(StandardColor color){
    setBackgroundColor(color.getHexValue());
}
Now doesn’t matter what modification you do in StandardColor enum like introducing new constants or changing constant’s value, all dependents need not to be cared.

Saturday, December 10, 2011

Type Inference in Java

As part of Generics , Java language supports type safe programming. It allows a type or method to operate on objects of various types while providing compile-time type safety. The most common use case is while using Java Collection framework. For example if you define a list of string and trying to add integer value to the list, compiler throws error.
List list = new ArrayList();
//Compilation Error : he method add(int, String) in the type List is not applicable for the arguments (int)
list.add(10);

As a developer you may always notice redundancy in defining parameter type information in both the side of declaration. As off Java 1.6, language doesn’t provide any feature to overcome it.

Using Static Factory : One possible way to overcome this problem by using static factory methods. If you frequently use typed list or map in application then you can define generic static factory methods which returns you required typed map or list.

public static   HashMap getMapInstance(){    
    return new HashMap();
}
public static  ArrayList getTypedList(){    
    return new ArrayList();
}
Above code snippet defines two static generic factory methods, which returns of specific parameter type list or map. While using these factory methods, java automatically infer parameter types based on left side type declaration.

//Using Static factory Methods, 
Map> map2 = getMapInstance();
Map map3 = getMapInstance();
List doubleList = getTypedList();

Diamond feature in Java 7: In java 7 you can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond ’ <>.