Drawing AWT BufferedImage on SWT Canvas

I am trying to write a SWT component that can take and draw an instance java.awt.BufferedImage. My problem is that SWT Imageand AWT BufferedImageare incompatible: SWT components cannot draw java.awt.Image, AWT / Swing components cannot draw org.eclipse.swt.graphics.Image.

There are several approaches that try to solve this problem in other ways (which may also have some variations, but basically there are two):

All of them have flaws and did not live up to my expectations:

  • The first approach for converting SWT Imageto BufferedImageresults in poor performance for large images due to the creation of a new instance RGBfor each pixel.
  • The second approach has several disadvantages in usability. See "Workarounds" at the end of a related article.

This leads to the conclusion that I will try to write a component (based on org.eclipse.swt.widgets.Canvasor org.eclipse.swt.widgets.Composite) that allows you to draw directly BufferedImagewithout converting images.

My approach was to draw pixel by pixel. Therefore, I just needed to get an instance GC, go BufferedImagethrough the source line by line, from left to right and draw the corresponding one Colorwith GC.setForeground(Color color)and GC.drawPoint(int x, int y).

First, I created a new instance Colorfor each pixel, which uses a lot of memory and adds an additional delay, as it new Colorreceives system resources, and creating a new object for each pixel also takes its time.

(24 ) Color , . ( >= 600 ), , , .

, .

, , , SWT (SWT) Image, .

.

+4
1

"" BufferedImage Image, , 24- RGB. , .

final BufferedImage original = ImageIO.read(new File("some-image.jpg");

final PaletteData palette =
        new PaletteData(0x0000FF, 0x00FF00, 0xFF0000);

// the last argument contains the byte[] with the image data
final ImageData data = new ImageData(original.getWidth(), original.getHeight(),
        24, palette, 4,
        ((DataBufferByte) original.getData().getDataBuffer()).getData());

final Image converted = new Image(getDevice(), data);

, . , , RGB 24 . .

:

// get the GC of your component
gc.drawImage(image, 0, 0);

, , , .

+2

Source: https://habr.com/ru/post/1544722/


All Articles