package ie.dcu.segment.util; import org.eclipse.swt.graphics.*; /** * Converts an SWT ImageData object to a linear array of bytes. * * @author Kevin McGuinness */ public class ImageByteConverter { private final int npixels; private final int nsamples; private final int[] pixels; private final byte[] samples; /** * Create an converter object for images of the given size. * * @param width * The image width. * @param height * The image height. */ public ImageByteConverter(int width, int height) { this.npixels = width*height; this.nsamples = npixels*3; this.pixels = new int[npixels]; this.samples = new byte[nsamples]; } /** * Convert an SWT ImageData object to a linear array of bytes. The returned * array contains three bytes per pixel, and is in row-major order. The * bytes are ordered RGB. * * @param data * An image data object. * @param clone * If false returns a shared array, otherwise returns a * new array. * @return A byte array of RGB values in row-major order. */ public byte[] convert(ImageData data, boolean clone) { PaletteData p = data.palette; data.getPixels(0, 0, npixels, pixels, 0); if (p.isDirect) { for (int i = 0, j = 0; i < npixels; i++) { // Unpack int r, g, b, pel = pixels[i]; // red r = pel & p.redMask; r = (p.redShift < 0) ? r >>> -p.redShift : r << p.redShift; // green g = pel & p.greenMask; g = (p.greenShift < 0) ? g >>> -p.greenShift : g << p.greenShift; // blue b = pel & p.blueMask; b = (p.blueShift < 0) ? b >>> -p.blueShift : b << p.blueShift; // assign samples[j++] = (byte) r; samples[j++] = (byte) g; samples[j++] = (byte) b; } } else { // Indirect palette for (int i = 0, j = 0; i < npixels; i++) { RGB color = p.colors[pixels[i]]; samples[j++] = (byte) color.red; samples[j++] = (byte) color.green; samples[j++] = (byte) color.blue; } } if (clone) { return samples.clone(); } return samples; } /** * Convert an SWT image data object to a linear array of bytes. The returned * array contains three bytes per pixel, and is in row-major order. The * bytes are ordered RGB. * * @param data * An image data object. * @return A byte array of RGB values in row-major order. */ public static byte[] convert(ImageData data) { return new ImageByteConverter(data.width, data.height).convert(data, false); } }