Assuming I have the Rectangle selection (x,y, width and height). Is it possible to get a Sub Image from an image in Java SWT?
I have an Image
on a Canvas
. The user selects a section of the image. I would like to replace the image with the users selection.
I cannot find a way to achieve this. Is the problem that I am using a Canvas
?
Update: This is my current method of doing it using drawImage. I guess this is a bit of a hack as I am not getting a Subset of the image and creating a new image - I am just drawing part of the Image:
int minX = Math.min(startX, endX);
int minY = Math.min(startY, endY);
int maxX = Math.max(startX, endX);
int maxY = Math.max(startY, endY);
int width = maxX - minX;
int height = maxY - minY;
gc.drawImage(image, minX, minY, width, height, image.getBounds().x,
image.getBounds().y, image.getBounds().width, image.getBounds().height );
You can use the method Canvas#copyArea(Image, int, int)
to copy just the area you're interested in to the given Image
. Then set the Image
to the Label
:
private static boolean drag = false;
private static int xStart;
private static int yStart;
private static int xEnd;
private static int yEnd;
private static Image outputImage = null;
public static void main(String[] args)
{
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("Stackoverflow");
shell.setLayout(new FillLayout());
Image inputImage = new Image(display, "baz.png");
Label output = new Label(shell, SWT.NONE);
Canvas canvas = new Canvas(shell, SWT.DOUBLE_BUFFERED);
canvas.addListener(SWT.Paint, e -> e.gc.drawImage(inputImage, 0, 0));
canvas.addListener(SWT.MouseDown, e -> {
xStart = e.x;
yStart = e.y;
drag = true;
});
canvas.addListener(SWT.MouseUp, e -> {
drag = false;
int x = Math.min(xStart, xEnd);
int y = Math.min(yStart, yEnd);
if (outputImage != null && !outputImage.isDisposed())
outputImage.dispose();
outputImage = new Image(display, new Rectangle(x, y, Math.abs(xEnd - xStart), Math.abs(yEnd - yStart)));
GC gc = new GC(inputImage);
gc.copyArea(outputImage, x, y);
output.setImage(outputImage);
gc.dispose();
});
canvas.addListener(SWT.MouseExit, e -> drag = false);
canvas.addListener(SWT.MouseMove, e -> {
if (drag)
{
xEnd = e.x;
yEnd = e.y;
}
});
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
inputImage.dispose();
if (outputImage != null && !outputImage.isDisposed())
outputImage.dispose();
}
Looks like this:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.