使用 SWT 在 Eclipse 插件透视图中加载 BMP

Loading a BMP in an Eclipse Plugin Perspective using SWT

我在字节数组中有一个 BMP。我想使用 SWT 在 Eclipse 插件中显示 BMP。

如果我想使用 swing 显示 BMP - 可以按如下方式完成:

    BufferedImage bufferedImage = null;
    try {
        bufferedImage = ImageIO.read(new ByteArrayInputStream(getLocalByteArray()));
    } catch (IOException ex) {

    }

    JLabel jLabel = new JLabel(new ImageIcon(bufferedImage));

    JPanel jPanel = new JPanel();
    jPanel.add(jLabel);
    this.add(jPanel);

更新: BMP 将表示为字节数组。这是这个的先决条件。

如何使用 SWT 在 Eclipse 插件中执行此操作?请注意,我正在使用透视图。

SWT Image 可以直接从输入流创建。支持多种数据格式,包括 Windows 格式的 BMP。

例如:

Image image = new Image( display, new ByteArrayInputStream( ... ) );

生成的图像可以在 Label 上设置或在其他地方使用。

您可以简单地在 Image 构造函数中指定文件,然后将其设置为 Label.

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());

    Label label = new Label(shell, SWT.NONE);
    Image image = new Image(display, "image.bmp");
    label.setImage(image);

    shell.pack();
    shell.open();

    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
        {
            display.sleep();
        }
    }
    display.dispose();

    image.dispose();
}

请记住,您必须自己 dispose() 图像才能避免内存泄漏。

好的 - 我明白了。由于代码很短,我已经包含了上下文:

public void createPartControl(Composite parent) {
    try {
        BufferedInputStream inputStream = new BufferedInputStream(new ByteArrayInputStream(getLocalByteArray()));
        ImageData imageData = new ImageData(inputStream);
        Image image = ImageDescriptor.createFromImageData(imageData).createImage();


        // Create the canvas for drawing
        Canvas canvas = new Canvas( parent, SWT.NONE);
        canvas.addPaintListener( new PaintListener() {
        public void paintControl(PaintEvent e) {
        GC gc = e.gc;
        gc.drawImage( image,10,10);
        }
        });