You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java读取配置文件中Base64图片时getProperty方法失效如何解决

Base64编码图片解码失败问题排查与解决方案

问题原因

  • 配置路径设置时机错误:加载icon.properties的代码执行顺序早于jagacy.properties.dir系统属性设置,加载配置时自定义配置目录未生效,无法读取到目标配置文件,导致getProperty("icon")返回空值调用失败。
  • 配置加载路径冗余:设置配置目录为src/test/resources/img后,读取配置时不需要再加img/前缀,否则会拼接出src/test/resources/img/img/icon.properties的错误路径,同样会导致读取配置失败。
  • Base64内容包含非法前缀:icon.properties中存储的是Data URI格式的Base64内容,前缀data:image/png;base64,不属于合法Base64编码内容,直接解码会生成非法字节数组,无法识别为图片。

解决方案

调整代码逻辑,修正后的完整代码如下:

Image icon = null;
// 先设置配置目录,再加载配置文件
System.setProperty("jagacy.properties.dir", "src/test/resources/img");
// 配置目录已指向img文件夹,直接读取文件名即可
Properties properties = ReadProperties.readFromConfig("icon.properties");

// 读取配置并判空,避免空指针
String iconBase64WithPrefix = properties.getProperty("icon");
if (iconBase64WithPrefix == null || iconBase64WithPrefix.isBlank()) {
    throw new IllegalArgumentException("未读取到icon配置项,请检查配置文件路径是否正确");
}

// 移除Data URI前缀后再解码
String pureIconBase64 = iconBase64WithPrefix.split(",")[1];
byte[] decoded = Base64.decode(pureIconBase64);
icon = Image.getInstance(decoded);

内容的提问来源于stack exchange,提问作者Yerko Ariel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 05:48:03