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);
}