Java 如何将图像表达式设置为始终存储正确的图像路径

Java 如何将图像表达式设置为始终存储正确的图像路径,java,image,jasper-reports,expression,Java,Image,Jasper Reports,Expression,我使用JasperReports通过Java动态创建报告。我对图像表达式(图像路径)有问题。这就是我现在通过它的方式: JRDefaultStyleProvider JRDefaultStyleProvider = null; JRDesignImage image = new JRDesignImage(JRDefaultStyleProvider); image.setX(0); image.setY(0); image.setWidth(200); image.setHeight(200)

我使用JasperReports通过Java动态创建报告。我对图像表达式(图像路径)有问题。这就是我现在通过它的方式:

JRDefaultStyleProvider JRDefaultStyleProvider = null;
JRDesignImage image = new JRDesignImage(JRDefaultStyleProvider);
image.setX(0);
image.setY(0);
image.setWidth(200);
image.setHeight(200);
exp = new JRDesignExpression();
**exp.setText("\"D:/MyProgram/src/myprogram/images/logo.png\"");**
image.setExpression(exp);
image.setStyle(styles.imageStyle);
title_band.addElement(image);
它可以正常工作,但是如果我更改程序的位置,我还必须更改表达式中的路径。
我尝试将表达式设置为:
。/images/logo.png
,但出现了一个错误:“在:../images/logo.png中找不到字节数据”。任何帮助都将不胜感激

你可以做几件事

一种是在报告中手动添加名为ProjectRoot的参数,使用
$p{ProjectRoot}+“images/logo.png”
作为图像表达式,并在运行报告时传递ProjectRoot的值(取自环境)

另一种方法是利用JasperReports还试图将图像位置解析为类加载器资源这一事实。因此,如果您添加src/myprogram作为源文件夹,以便images/logo.png在运行时成为项目类路径的一部分,那么您将能够使用
“images/logo.png”
作为图像表达式

第三种解决方案是在用于填充报表的
JasperReportsContext
实例中注册
FileRepositoryService
扩展。文件存储库服务将使用当前项目根路径创建,您需要从环境中确定该路径。拥有存储库服务还允许您使用
“images/logo.png”
作为图像表达式。代码如下所示:

SimpleJasperReportsContext context = new SimpleJasperReportsContext();
FileRepositoryService fileRepository = new FileRepositoryService(context, "D:/MyProgram/src/myprogram/", false);
context.setExtensions(RepositoryService.class, Collections.singletonList(fileRepository));
context.setExtensions(PersistenceServiceFactory.class, Collections.singletonList(FileRepositoryPersistenceServiceFactory.getInstance()));

JasperPrint jasperPrint = JasperFillManager.getInstance(context).fill(jasperReport, params);