Im using Java swt Images with full 32-bit color and alpha channels (org.eclipse.swt.graphics.Image). I need to extract a rectangle of the image as a new image, including full alpha channel information.
For example, I may have a 100 × 100 image, and I need to create a new image with only a 50x pixel in the upper left corner, just like in a 100 × 100 image. (Im chopping, not rescaling.)
My initial attempt was to create an empty image of the required size (50 × 50 in this example), then get the GC for the new image, and then draw the correct part of the old image on the new image. The problem was that transparency was not preserved. If my new image starts opaque, the result after the draw will be completely opaque. If my new image becomes transparent, the result after drawing will be completely transparent (all RGB colors will be correct, but invisible, because alpha will be zero for all pixels).
My current solution is awkward: I use GC to draw an image, and then manually copy the alpha channel line by line.
private static Image getRectHelper(final Image source, final ImageData sourceData,
final int xInSource, final int yInSource, final int widthInSource, final int heightInSource, final Display disp)
{
final Display d = disp==null ? Display.getDefault() : disp;
final Image dest = new Image(d, widthInSource, heightInSource);
final GC g = new GC(dest);
g.drawImage(source, xInSource, yInSource, widthInSource, heightInSource, 0, 0, widthInSource, heightInSource);
g.dispose();
final ImageData destData = dest.getImageData();
copyAlpha(sourceData, destData, xInSource, yInSource, widthInSource, heightInSource, 0, 0);
final Image ret = new Image(d, destData);
dest.dispose();
return ret;
}
private static void copyAlpha(final ImageData sourceData, final ImageData destData,
final int xInSource, final int yInSource, final int width, final int height,
final int xInDest, final int yInDest)
{
final byte[] alphas = new byte[width];
for (int ySrc = yInSource, yDst = yInDest; ySrc < yInSource+height; ++ySrc, ++yDst) {
sourceData.getAlphas(xInSource, ySrc, width, alphas, 0);
destData.setAlphas(xInDest, yDst, width, alphas, 0);
}
}
? Java, - . - swt? , . Im ImageData GC.