gpt4 book ai didi

java - 如何将 SWT 图像转换为数据 URI 以在浏览器小部件中使用

转载 作者:行者123 更新时间:2023-11-30 04:10:26 25 4
gpt4 key购买 nike

我正在尝试在浏览器小部件(SWT)中显示图像。这些图像可以在 jar 文件中找到(插件开发)。然而:这并不是直接可能的,因为浏览器小部件需要某种 URL 或 URI 信息。

我的想法是将 SWT 图像转换为 data-URI 值,我可以将其引入每个给定 img 元素的 src 属性中。我知道,从性能角度来看这不是一个好的解决方案,但我不介意速度上的劣势。

我想知道如何将 SWT 图像转换为数据 URI 值以在浏览器小部件中使用

到目前为止我的代码:

package editor.plugin.editors.htmlprevieweditor;

import editor.plugin.Activator;

import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;

public class HtmlPreview extends Composite implements DisposeListener {

private final Browser content;

public HtmlPreview(final Composite parent, final int style) {
super(parent, style);

this.setLayout(new FillLayout());

content = new Browser(this, style);
final ImageData imageData = Activator.getImageDescriptor(Activator.IMAGE_ID + Activator.PREVIEW_SMALL_ID).getImageData();
content.setText("<html><body><img src=\"data:image/png;base64," + imageData + "\"/></body></html>"); // need help on changing imageData to a base64-encoded String of bytes?

this.addDisposeListener(this);

}

@Override
public void widgetDisposed(final DisposeEvent e) {
e.widget.dispose();
}
}

非常感谢任何帮助:)!

编辑1:我已阅读SWT Image to/from String ,但不幸的是它似乎并不能完全满足我的需求。

编辑 2:我不知道这是否重要,但我正在尝试加载具有每像素 alpha 透明度的 PNG24 图像。

最佳答案

如果您只说“SWT 中的浏览器”,那么这个问题就太笼统了。 Mozzila浏览器支持jar URL协议(protocol),你可以这样做:

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

final URL url = ShellSnippet.class.getResource("/icons/full/message_error.gif");
final Browser browser = new Browser(shell, SWT.MOZILLA);
final String html = String.format("<html><head/><body>image: <img src=\"%s\"/></body></html>", url);
browser.setText(html);

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

看起来像这样:

enter image description here

我使用了 JFace jar 中的图像来保持代码片段简单,并且开箱即用,适合大多数人。它是 GIF,但我希望它能够与 PNG 文件一样工作。

如果您使用 Internet Explorer,我不推荐这样做,因为您的应用程序取决于操作系统版本,这不起作用。它看起来像这样(在代码片段中将样式从 SWT.MOZILLA 更改为 SWT.NONE 后):

enter image description here

但是它确实理解file协议(protocol),您可以将文件复制到临时文件夹并使用File.toURL()直接创建指向该文件的URL。这应该适用于任何浏览器。

我无法在 WEBKIT 浏览器上测试简单的解决方案。如果有人可以,请在评论中发布结果。

关于java - 如何将 SWT 图像转换为数据 URI 以在浏览器小部件中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19745803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com