2013-11-02 20 views
1

我想顯示一個瀏覽器插件(SWT)內的圖像。這些圖像可以在jar文件中找到(插件開發)。但是:這不是直接可能的,因爲瀏覽器小部件需要某種URL或URI信息。如何SWT圖像轉換成數據URI在瀏覽器的插件使用

我的想法是將SWT圖像轉換爲數據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:我不知道它是否重要,但我試圖加載一個PNG24圖像與每像素alpha透明度。

回答

2

的問題是過於籠統,如果你只說「在SWT瀏覽器」。 Mozzila瀏覽器支持jar URL協議,你可以這樣做:

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

它看起來像這樣:

​​

我使用JFace的廣口瓶中的圖像,以保持片段簡單,但工作對於大多數人而言。它是GIF,但我希望它和PNG文件一樣好用。

如果您使用Internet Explorer,我不建議這樣做,因爲您的應用程序依賴於操作系統版本,但這不起作用。它看起來像這樣(從SWT.MOZILLA的片斷改變風格SWT.NONE後):

enter image description here

但它確實瞭解file的協議,可以將文件複製到臨時文件夾,並創建網址直接使用File.toURL()對文件進行操作。這應該適用於任何瀏覽器。

我無法在WEBKIT broswer上測試簡單的解決方案。如果有人可以,請將結果發佈在評論中。

+0

我讀過,除非指定SWT.MOZILLA並確保xulrunner.exe位於類路徑中,否則我無法在Windows計算機上使用Mozilla-Browser-widget。這意味着它會是相當困難的使用Mozilla的瀏覽器插件 - 儘管我很感激,因爲這支持它。 我會嘗試一下!非常感謝你的提示。只要我想出一種使用Mozilla-Browser-widget的方式,我會將這個答案標記爲正確的答案,除非有人提供了更好的答案。 – Igor

+0

@Igor在我來說,我只是說:System.setProperty( 「org.eclipse.swt.browser.XULRunnerPath」, 「路徑XULRunner的」);並且xul亞軍被複制在「通往xulrunner的道路上」。 – andi

相關問題