title: Drawing AWT BufferedImage on SWT Canvas
body: <p>I am trying to write a SWT component, that is able to take and draw an instance of <code>java.awt.BufferedImage</code>. My problem is that SWT's <code>Image</code> and AWT's <code>BufferedImage</code> are incompatible: SWT components can't draw <code>java.awt.Image</code>, AWT/Swing components can't draw <code>org.eclipse.swt.graphics.Image</code>.</p>
  
  <p>There are several approaches that try to solve this problem in other ways (which also may have some variations, but basically there are these two):</p>
  
  <ol>
  <li><a href="http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/ConvertbetweenSWTImageandAWTBufferedImage.htm" rel="noreferrer">Convert between SWT Image and AWT BufferedImage</a></li>
  <li><a href="http://www.eclipse.org/articles/article.php?file=Article-Swing-SWT-Integration/index.html" rel="noreferrer">Swing/SWT Integration</a></li>
  </ol>
  
  <p>They all have shortcomings and didn't satisfy my expectations:</p>
  
  <ol>
  <li>The first approach, to convert an SWT <code>Image</code>  to a <code>BufferedImage</code>, results in poor performance for large images due to the creation of a new <code>RGB</code> instance for every Pixel.</li>
  <li>The second approach has several shortcomings in usability. See the "workarounds" at the end of the linked article.</li>
  </ol>
  
  <p>This lead to the conclusion that I'd try my best to write a component (based on <code>org.eclipse.swt.widgets.Canvas</code> or <code>org.eclipse.swt.widgets.Composite</code>) which allows to draw a <code>BufferedImage</code> directly without any conversion of images.</p>
  
  <p>My approach was to draw it pixel by pixel. Therefore I simply had to get an instance of <code>GC</code>, walk the source <code>BufferedImage</code> line by line, left-to-right and drawing the corresponding <code>Color</code> using <code>GC.setForeground(Color color)</code> and <code>GC.drawPoint(int x, int y)</code>.</p>
  
  <p>First, I created a new instance of <code>Color</code> for every pixel, which uses quite a lot of memory and adds an additional delay, since <code>new Color</code> acquires system resources and creating a new object for every pixel also takes its time.</p>
  
  <p>Then I tried to pre-load all possible (24 bit) <code>Color</code>s into an array before drawing the image. This lead to an explosion of memory usage (>= 600 MB), which was clear before I was trying it, but I had to verify it.</p>
  
  <p>Caching only the used Colors also lead to more memory consumption than would have been required.</p>
  
  <p>I think there has to be a more low-level approach that doesn't require that much memory, since SWT is able to draw whole (SWT) <code>Image</code>s without consuming that much memory.</p>
  
  <p>I would appreciate any ideas or solutions.</p>