如何编组 JavaFX 图像并将其绝对路径保存在 xml 中

How to marshal JavaFX Image and save its absolute path in xml

所以我一直在开发地址管理器应用程序,遇到这样一种情况,我必须将每个人的图像和其他数据一起保存到 xml 文件中 在本地磁盘上。如何实现图片的marshalling/unmarshalling?

这是人class。

//relevant imports ..


public class Person {

    private final StringProperty firstName;
    private final StringProperty lastName;
    private final StringProperty address;
    private final IntegerProperty zipCode;
    private final SimpleStringProperty contact;
    private final StringProperty city;
    private final ObjectProperty<LocalDate> birthday;
    private final ObjectProperty<Image> image;

     //constructors
    public Person() {
        this(null, null);
    }

    public Person(String firstName, String lastName) {

        this.firstName = new SimpleStringProperty(firstName);
        this.lastName = new SimpleStringProperty(lastName);
        this.address = new SimpleStringProperty("");
        this.city = new SimpleStringProperty("Amroha");
        this.contact = new SimpleStringProperty("");
        this.zipCode = new SimpleIntegerProperty(244221);
        this.birthday = new SimpleObjectProperty<LocalDate>(LocalDate.of(1993, Month.JANUARY, 6));
        this.image=new SimpleObjectProperty<Image>(null);
    }

    // other getters & setters..

    public void setImage(Image image) {

        this.image.set(image);
    }

    public Image getImage() {
        return image.get();

    }

}

我创建了这个 XML 适配器 用于将图像解析到 xml 我想 存储图像文件路径作为

public class ImageAdapter extends XmlAdapter<String,Image>{

    @Override
    public Image unmarshal(String filePath) throws Exception {

        return new Image("file :"+filePath);
    }

    @Override
    public String marshal(Image v) throws Exception {

        //don't know what to do here..

    }
}

Image.url 属性 仅从 JavaFX 9 开始可用。对于从 InputStream.

创建的图像也不起作用

在 JavaFX 8 中恢复图像路径需要您在加载图像时自行存储 URL。为此,您可以使用 Map

private final Map<Image, String> imageSources = new WeakHashMap();

public Image loadImage(String url) {
    Image image = new Image(url);
    imageSources.put(image, url);
    return image;
}

public String getURLFromImage(Image image) {
    retrun imageSources.get(image);
}

这有一个缺点,即数据分布在多个文件中。将数据移动到不同的机器需要移动所有引用的文件,除非您实现额外的逻辑来使 url 相对,否则您将获得绝对路径,使数据更难移动...


您可以将图像数据作为 base64 编码字符串存储在 xml 本身中:

public class ImageAdapter extends XmlAdapter<String, Image>{

    @Override
    public Image unmarshal(String data) throws Exception {
        return data == null || data.isEmpty() ? null : new Image(new ByteArrayInputStream(Base64.getDecoder().decode(data)));
    }

    @Override
    public String marshal(Image v) throws Exception {
        if (v == null) {
            return "";
        }
        BufferedImage bImg = SwingFXUtils.fromFXImage(v, null);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(bImg, "png", bos);

        return Base64.getEncoder().encodeToString(bos.toByteArray());
    }
}