Android从Sqlite数据库保存并获取图像

时间:2016-03-10 13:18:16

标签: java android sqlite android-studio

逗人 我怎样才能保存图像并从Sqlite数据库中获取图像我正在使用Android Studio?

2 个答案:

答案 0 :(得分:2)

可能为时已晚。但对未来的读者很有用..

import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;


import java.util.HashMap;

 /**
  * Created by Noorul on 23-05-2016.
 */

@SuppressWarnings("ALL")
public class DBSplash extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "SplashDB.db";
public static final String SPLASH_TABLE_NAME = "splash_db";

private HashMap hp;

public DBSplash(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(
            "create table " + SPLASH_TABLE_NAME + "( name TEXT, image BLOB)"
    );
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS contacts");
    onCreate(db);
}

public boolean insertImage(String name, Bitmap img) {
    Bitmap storedBitmap = null;
    String sql = "INSERT INTO " + SPLASH_TABLE_NAME + " (name,image) VALUES(?,?)";
    SQLiteDatabase db = this.getWritableDatabase();
    SQLiteStatement insertStmt = db.compileStatement(sql);

    byte[] imgByte = getBitmapAsByteArray(img);
    try {
        storedBitmap = getImage(name);
    } catch (Exception e) {
        AppLog.exception(e);
    }
    if (storedBitmap == null) {
        insertStmt.bindString(1, name);
        insertStmt.bindBlob(2, imgByte);
        insertStmt.executeInsert();
        db.close();
    }
    return true;
}


public int numberOfRows() {
    SQLiteDatabase db = this.getReadableDatabase();
    int numRows = (int) DatabaseUtils.queryNumEntries(db, SPLASH_TABLE_NAME);
    return numRows;
}


public Bitmap getImage(String name) {
    String qu = "SELECT * FROM " + SPLASH_TABLE_NAME;
    Cursor cur = null;
    SQLiteDatabase db = this.getReadableDatabase();

    try {
        cur = db.rawQuery(qu, new String[]{});
    } catch (Exception e) {
        AppLog.exception(e);
    }
    if (cur != null) {
        if (cur.moveToFirst()) {
            int index = cur.getColumnIndexOrThrow("image");
            byte[] imgByte = cur.getBlob(index);
            cur.close();
            return BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
        }
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }
    }

    return null;
}
   public byte[] getBitmapAsByteArray(Bitmap bitmap) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 0, outputStream);
    return outputStream.toByteArray();
}
}

使用此代码。但是,将数据存储在数据库中并非最佳实践。如果您需要不模糊的图像,请更改图像大小。 IM是具有高内存的blob类型。手机是较小的设备。所以在sqlite db中存储许多图像意味着,它会很难看。所以使用@thongong方法

答案 1 :(得分:0)

您可以查看本教程以在Android中实现Sqlite。 http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

而是使用Contact,例如,您可以实现这种方式

public class Image{
    String imagePath; //it is your absolute image file path
}

您的DatabaseHandler可以像下面这样实施

public class DatabaseHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "imagedb";

    // Contacts table name
    private static final String TABLE_IMAGE = "images";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_IMAGE_PATH = "name";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sqlQuery = "CREATE TABLE " + TABLE_IMAGE + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_IMAGE_PATH + " TEXT)";
        db.execSQL(sqlQuery);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_IMAGE);

        // Create tables again
        onCreate(db);
    }

    // Adding new image
    public void addImage(Image image) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_IMAGE_PATH, image.imagePath); // Image path

        // Inserting Row
        db.insert(TABLE_IMAGE, null, values);
        db.close(); // Closing database connection
    }


    // Getting single image
    public Image getImage(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_IMAGE, new String[] { KEY_ID,
                        KEY_IMAGE_PATH}, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Image image = new Image(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1));
        // return image
        return image;
    }
}