经过深思熟虑后,我发现了一些将Buffered
Image转换为SWT图像的代码(暂不阅读它):
public static ImageData convertToSWT(BufferedImage bufferedImage) { if (bufferedImage.getColorModel() instanceof DirectColorModel) { DirectColorModel colorModel = (DirectColorModel) bufferedImage.getColorModel(); PaletteData palette = new PaletteData( colorModel.getRedMask(),colorModel.getGreenMask(),colorModel.getBlueMask() ); ImageData data = new ImageData( bufferedImage.getWidth(),bufferedImage.getHeight(),colorModel.getPixelSize(),palette ); WritableRaster raster = bufferedImage.getRaster(); int[] pixelArray = new int[3]; for (int y = 0; y < data.height; y++) { for (int x = 0; x < data.width; x++) { raster.getPixel(x,y,pixelArray); int pixel = palette.getPixel( new RGB(pixelArray[0],pixelArray[1],pixelArray[2]) ); data.setPixel(x,pixel); } } return data; } else if (bufferedImage.getColorModel() instanceof IndexColorModel) { IndexColorModel colorModel = (IndexColorModel) bufferedImage.getColorModel(); int size = colorModel.getMapSize(); byte[] reds = new byte[size]; byte[] greens = new byte[size]; byte[] blues = new byte[size]; colorModel.getReds(reds); colorModel.getGreens(greens); colorModel.getBlues(blues); RGB[] rgbs = new RGB[size]; for (int i = 0; i < rgbs.length; i++) { rgbs[i] = new RGB(reds[i] & 0xFF,greens[i] & 0xFF,blues[i] & 0xFF); } PaletteData palette = new PaletteData(rgbs); ImageData data = new ImageData( bufferedImage.getWidth(),palette ); data.transparentPixel = colorModel.getTransparentPixel(); WritableRaster raster = bufferedImage.getRaster(); int[] pixelArray = new int[1]; for (int y = 0; y < data.height; y++) { for (int x = 0; x < data.width; x++) { raster.getPixel(x,pixelArray); data.setPixel(x,pixelArray[0]); } } return data; } return null; }
(见于:http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/ConvertsabufferedimagetoSWTImageData.htm).
我测试过它,它运行得很好.问题是我不理解它(我最好的猜测是它使用两者的原始数据接口来进行传输).在我看来,一个更简单的解决方案是将BufferedImage写入ByteArrayOutputStream,然后将其读回SWT Image withByteArrayInputStream.这个解决方案有什么问题吗?速度怎么样?
这种转换是必要的,因为所有图像大小调整库都用于AWT,但我用SWT显示图像.
谢谢!