如何将图像保存到Room Persistence Library [英] How to save images to Room Persistence Library

查看:160
本文介绍了如何将图像保存到Room Persistence Library的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最初,我是在卡片视图中添加信息(字符串)和照片(来自可绘制对象).我让它从列表中工作,并使用适配器等将其添加到回收者视图中的卡中.现在,我尝试迁移到使用Room Persistence库保存此信息,而不是在代码中添加虚拟信息,而是让它来自用户输入,因为我正在尝试实现这一点,因此我发现保存图像到Room DB不太容易.现在,字符串可以正常工作了,我只需要一种方法来保存从相机拍摄后的图像.

Originally I was adding information (Strings) and a photo (from drawable) to card views. I had it working from a list and adding it to the cards within a recycler view using an adapter and such. Now I'm trying to migrate to saving this information using the Room Persistence Library and instead of adding dummy info in the code I am going to make it come from user input, as I'm trying to implement this I have discovered that saving images to Room DB is not too easy. The strings are working fine now I just need a way to save the images after taken from the camera.

我无法使用图像",位图","URI",可绘制对象"类型将图像存储在Room DB中.

I can't store images in the Room DB using types Image, Bitmap, URI, Drawables.

@Entity(tableName = "machines_table")
public class Machines {


    @PrimaryKey(autoGenerate = true)
    private int id;
    private Drawable photoId;
    private String name;
    private String location;

    public Machines(String name, String location, Drawable photoId) {
        this.name = name;
        this.location = location;
        this.photoId = photoId;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public String getLocation() {
        return location;
    }

    public Drawable getPhotoId() {
        return photoId;
    }

}

我想我希望能够更轻松地保存图像,但是当使用上面列出的任何一种类型时,情况并非如此.

I guess I expected to be able to save images more easily however this is not the case when using any of the types I listed above I am given this error.

错误:无法弄清楚如何将该字段保存到数据库中.您可以考虑为其添加类型转换器."

"error: Cannot figure out how to save this field into database. You can consider adding a type converter for it."

推荐答案

您可能可以将它们另存为byte[],但是将位图保存到数据库通常被认为是不明智的.将它们存储到文件系统,然后将文件名(例如,基于UUID的文件名)保存到DB.然后在需要时检索文件.

You'll probably are able to save them as byte[], however it is generally regarded as unwise to save bitmaps to the DB. Store them to the filesystem and save the filename (a UUID based one for example) to the DB. Then retrieve the file when needed.

如果数据库本身存储图像,则数据库将变得庞大而缓慢.

The database would become huge and slow if it stores the images themselves.

这篇关于如何将图像保存到Room Persistence Library的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆