在eclipse插件开发的时候,很多地方都需要用到图片之类的资源,而在SWT中图片资源是需要手动释放的。虽然操作不难,但是手动释放时机却很难把握,尤其是图片可能被多个地方用到的时候。在网上看了一个帖子:
http://southking.iteye.com/blog/316449对资源的解释还是蛮详细的,但是也没有提供一个简单的图片管理实现。这里把自己的简单实现图片资源管理的代码贴出来:
public static ImageDescriptor findImageDescriptor(String path)
{
final IPath p = new Path(path);
if (p.isAbsolute() && p.segmentCount() > 1)
{
return AbstractUIPlugin.imageDescriptorFromPlugin(p.segment(0), p.removeFirstSegments(1).makeAbsolute()
.toString());
} else
{
return getBundledImageDescriptor(p.makeAbsolute().toString());
}
}
private static ImageDescriptor getBundledImageDescriptor(String path)
{
return AbstractUIPlugin.imageDescriptorFromPlugin(PLUGIN_ID, path);
}
public Image getBundledImage(String path)
{
Image image = getImageRegistry().get(path);
if (image == null)
{
getImageRegistry().put(path, getBundledImageDescriptor(path));
image = getImageRegistry().get(path);
}
return image;
}
上述是加载插件里面的图片资源,位置也是相对当前插件工程的。
下面贴一点其他的:
1.使用Image(Device device, InputStream stream)构造函数,示例代码如下, path为图像相对路径:
如下是官方提供的例子:
static Image loadImage (Display display, Class clazz, String string) {
InputStream stream = clazz.getResourceAsStream (string);
if (stream == null) return null;
Image image = null;
try {
image = new Image (display, stream);
} catch (SWTException ex) {
} finally {
try {
stream.close ();
} catch (IOException ex) {}
}
return image;
}
如下是我自己的实现:
/**
*
* @param file 传入的对象必须为图片对象
* @return
* @throws CoreException
*/
public static Image getImage(IFile file) throws CoreException
{
if (file == null || file.exists())
{
return null;
}
Image image = JFaceResources.getImage(file.toString());
if (image == null || image.isDisposed())
{
image = new Image(Display.getCurrent(), file.getContents());
JFaceResources.getImageRegistry().put(
file.getFullPath().toOSString(), image);
}
return image;
}
2.使用ImageDescriptor的createImage()方法,示例代码如下,path为图像相对路径:
private Image getImage(String path){
URL url = null;
try{
url = new URL(Activator.getDefault().getDescriptor().getInstallURL(), path);
}catch(MalformedURLException e){
e.printStackTrace();
}
ImageDescriptor imageDescriptor = ImageDescriptor.createFromURL(url);
return imageDescriptor.createImage();
}
private Image getImage(String path){
ImageDescriptor desc = AbstractUIPlugin.imageDescriptorFromPlugin(ID, path);
return desc.createImage();
}