SWT:从图像中获取子图像

时间:2016-05-30 08:03:57

标签: java image-processing swt

假设我有矩形选择(x,y,宽度和高度)。是否可以从Java SWT中的图像中获取子图像?

Image上有一个Canvas。用户选择图像的一部分。我想用用户选择替换图像。

我找不到实现这个目标的方法。问题是我使用的是Canvas吗?

更新: 这是我目前使用drawImage完成它的方法。我想这有点像黑客,因为我没有获得图像的子集并创建新图像 - 我只是绘制图像的一部分:

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

1 个答案:

答案 0 :(得分:2)

您可以使用方法Canvas#copyArea(Image, int, int)将您感兴趣的区域复制到给定的Image。然后将Image设置为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();
}

看起来像这样:

enter image description here