首先获取ImageIO里的注册机
private static final IIORegistry registry;
static
{
IIORegistry temp = null;
try
{
Field field = ImageIO.class.getDeclaredField("theRegistry");
field.setAccessible(true);
temp = (IIORegistry)field.get(null);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (temp == null) {
temp = IIORegistry.getDefaultInstance();
}
registry = temp;
}
}
然后网注册机里注册读写类
public static void registerServiceProvider(Class<?> clazz)
{
Class<?> spiClass = null;
try
{
spiClass = Class.forName(clazz.getName(), true, ClassLoader.getSystemClassLoader());
}
catch (ClassNotFoundException localClassNotFoundException) {}
if (spiClass != null)
{
Object spi = registry.getServiceProviderByClass(spiClass);
if (spi != null) {
registry.deregisterServiceProvider(spi);
}
}
try
{
registry.registerServiceProvider(clazz.newInstance());
}
catch (Exception e)
{
e.printStackTrace();
}
}
这样ImageIO就保留了格式和读写类的对应关系
读写时通过以下代码皆可以调用到读写类
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(param.formatName);
while (readers.hasNext()) {
ImageReader reader = readers.next();
if (param.className == null || param.className.equals(reader.getClass().getName())) {
LOG.debug("Using Image Reader {}", reader.getClass());
return reader;
}
}