如何将图像插入数据库?

时间:2015-04-29 04:01:40

标签: android

所以,我有一个存储食谱的数据库。现在,Recipe表只保存了名称,类型等数据。但是,由于我想在应用程序中显示每个食谱的图片,我需要以某种方式将图像存储到数据库中,但我不知道知道如何。

到目前为止我所拥有的是什么

public class DBHandler extends SQLiteOpenHelper{

//    private static class DatabaseHelper extends SQLiteOpenHelper {

        public static final String COLUMN_ROWID = "_id";
        public static final String COLUMN_NAME = "name";
        public static final String COLUMN_TYPE = "type";
        public static final String COLUMN_INGRED = "ingred";

        private static final String TAG = "DBHandler";
        //private DatabaseHelper mDbHelper;
        //private SQLiteDatabase mDb;

        private static final String DATABASE_NAME = "Recipes";
        private static final String SQLITE_TABLE = "TABLE_RECIPES";
        private static final int DATABASE_VERSION = 1;

        //private final Context mCtx;
    public DBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
/*        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }*/

        @Override
        public void onCreate(SQLiteDatabase db) {
            String DATABASE_CREATE =
                    "CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
                            COLUMN_ROWID + " integer PRIMARY KEY autoincrement," +
                            COLUMN_NAME + "," +
                            COLUMN_TYPE + "," +
                            COLUMN_INGRED + ")";

            Log.w(TAG, DATABASE_CREATE);
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
            onCreate(db);
        }

/*    public DBHandler(Context ctx) {
        this.mCtx = ctx;
    }*/
/*
    public DBHandler open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }*/

/*    public void close() {
        if (mDbHelper != null) {
            mDbHelper.close();
        }
    }*/

    public void createRecipe(String name,
                              String type, String ingred) {

        ContentValues initialValues = new ContentValues();
        //initialValues.put(COLUMN_CODE, code);
        initialValues.put(COLUMN_NAME, name);
        initialValues.put(COLUMN_TYPE, type);
        initialValues.put(COLUMN_INGRED, ingred);

        SQLiteDatabase db = this.getWritableDatabase();
        db.insert(SQLITE_TABLE, null, initialValues);
        db.close();
    }

    public boolean deleteAllRecipes() {
        int doneDelete = 0;

        SQLiteDatabase mDb = this.getWritableDatabase();
        doneDelete = mDb.delete(SQLITE_TABLE, null , null);
        Log.w(TAG, Integer.toString(doneDelete));
        return doneDelete > 0;

    }

    public Cursor fetchRecipesByName(String inputText) throws SQLException {
        SQLiteDatabase mDb = this.getWritableDatabase();
        Log.w(TAG, inputText);
        Cursor mCursor = null;
        if (inputText == null  ||  inputText.length () == 0)  {
            mCursor = mDb.query(SQLITE_TABLE, new String[] {COLUMN_ROWID,
                            COLUMN_NAME, COLUMN_TYPE, COLUMN_INGRED},
                    null, null, null, null, null);

        }
        else {

            mCursor = mDb.query(true, SQLITE_TABLE, new String[] {COLUMN_ROWID,
                            COLUMN_NAME, COLUMN_TYPE, COLUMN_INGRED},
                    COLUMN_NAME + " like '%" + inputText + "%'" + " or " +
                            COLUMN_TYPE + " like '%" + inputText + "%'" + " or " +
                            COLUMN_INGRED + " like '%" + inputText + "%'",
                    null, null, null, null, null);
        }
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }


    public Cursor fetchAllRecipes() {
        SQLiteDatabase mDb = this.getWritableDatabase();

        Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {COLUMN_ROWID,
                        COLUMN_NAME, COLUMN_TYPE, COLUMN_INGRED},
                null, null, null, null, null);

        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    public void insertSomeRecipes() {

        createRecipe("Blackened Salmon","Dinner","Salmon");
    }

    public boolean deleteRecipe(String name){
        SQLiteDatabase mDb = this.getWritableDatabase();
        boolean result = false;

        String sql_query = "SELECT * FROM " + SQLITE_TABLE + " WHERE " + COLUMN_NAME + " = \"" + name + "\"";

        Cursor myCursor = mDb.rawQuery(sql_query, null);
        Recipes myRecipe = new Recipes();

        if (myCursor.moveToFirst()){
            myRecipe.setID(myCursor.getInt(0));
            mDb.delete(SQLITE_TABLE, COLUMN_ROWID + " = ?", new String[]{String.valueOf(myRecipe.getID())});
            myCursor.close();
            result = true;
        }

        mDb.close();
        return result;

    }

}

5 个答案:

答案 0 :(得分:1)

好的存储图像你可以试试这个

  • 如果您想保存非来自服务器并存储在drawable / mipmap文件夹中的图像,只需存储他们的ID

    initialValues.put(COLUMN_IMAGE,R.mipmap.demp);

  • 如果他们来自服务器或api,只需保存他们的网址并使用picaso等任何库加载它们。

我在我的应用程序中尝试了相同的功能。

答案 1 :(得分:0)

答案 2 :(得分:0)

将您的图像转换为base64编码的字符串,然后将该字符串插入数据库:

Bitmap bm = BitmapFactory.decodeFile("<path to your image>");
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);  
byte[] b = baos.toByteArray(); 
String encodedString = Base64.encodeToString(b, Base64.DEFAULT);  

当您获取字符串时,请将其转换为:

byte[] b= Base64.decode(encodedString , Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(b,0,b.length); 

答案 3 :(得分:0)

这是一种将位图图像存储到数据库中的方法,需要为数据库表中的图像指定一种列为Blob的列

(defun my-function (x y)
   (when x (return-from my-function y))
   ;;; more code
   )

答案 4 :(得分:0)

您可以遵循的最简单的技术是将您的Image路径作为String存储在数据库表中,然后您可以在需要该映像时将其恢复并使用BitmapFactory.decodeFile对其进行解码。存储Base64String很好,但是字符串太大了,如果你看到图像的路径它是一个相对较短的字符串

例如:

  • 在名为createRecipe()的{​​{1}}方法中定义另一个参数,如:

String imagePath

  • 当您调用此功能时,您将通过图像路径:

public void createRecipe(String name,String type, String ingred,String imgPath){}

要获得ImagePath,您可以执行以下操作:

createRecipe(name,type,ingred,path_of_image)
  • 最后,当您调用String destination = new File(Environment.getExternalStorageDirectory(), name_of_your_image+ ".jpg"); FileInputStream in = new FileInputStream(destination); String photoPath = destination.getAbsolutePath(); fetchRecipesByName()方法时,fetchAllRecipes()现在将针对每个条目存储您的路径,您可以将此路径作为字符串传递给下面的函数你将得到Bitmap作为回报。
Cursor

注意:如果您要存储图片的路径并且可以从图库中删除它也应该小心,以便作为回报您不能有任何针对此路径的位图,因此您应该管理图像是否为&# 39; t存在然后使用替代图像。

相关问题