【问题标题】:How to add image from url to Sqlite Database in Android and Retrieve them based on index如何将图像从 url 添加到 Android 中的 Sqlite 数据库并根据索引检索它们
【发布时间】:2017-10-12 18:54:56
【问题描述】:

我正在创建一个应用程序,我希望以后能够在不卸载应用程序的情况下更改图像。 由于我们无法写入可绘制文件夹,我想我使用数据库来保存图像,然后我可以在以后操作那里的数据。

我测试了一些代码,但它似乎不起作用。我可以从 url 中提取图像并显示。但我仍然无法弄清楚如何从 url 将图像放在数据库中。

看看我的代码。

public class MainActivity extends AppCompatActivity {
Intent intent;
Button btn;
DataBaseHandler db;
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    btn = (Button)findViewById(R.id.btn);
    final ImageView img = (ImageView)findViewById(R.id.img);
    //initialize db
    db = new DataBaseHandler(this);


    URL url = null;
    try {
        url = new URL("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQSh3goeAXlletPgkm3pm1F4DgxwArOKS9STyK02ocNn0AZ6Q9u");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    try {
        url = new URL("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQSh3goeAXlletPgkm3pm1F4DgxwArOKS9STyK02ocNn0AZ6Q9u");
        final Bitmap image = BitmapFactory.decodeStream(url.openStream());
        byte[]inpudata = Utils.getImageBytes(image);
        db.insertImage(inpudata);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                byte[]inpudata = db.retreiveImageFromDB();


                img.setImageBitmap(Utils.getImage(inpudata));
            }
        });
    } catch(IOException e) {
        System.out.println(e);
    }




}



 }

也是数据库助手类

public class DataBaseHandler{

public static final String IMAGE_ID = "id";
public static final String IMAGE = "image";
private final Context mContext;

private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;

private static final String DATABASE_NAME = "Images.db";
private static final int DATABASE_VERSION = 1;

private static final String IMAGES_TABLE = "ImagesTable";

private static final String CREATE_IMAGES_TABLE =
        "CREATE TABLE " + IMAGES_TABLE + " (" +
                IMAGE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + IMAGE + " BLOB NOT NULL );";


private static class DatabaseHelper extends SQLiteOpenHelper {
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_IMAGES_TABLE);
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + CREATE_IMAGES_TABLE);
        onCreate(db);
    }
}

public void Reset() {
    mDbHelper.onUpgrade(this.mDb, 1, 1);
}

public DataBaseHandler(Context ctx) {
    mContext = ctx;
    mDbHelper = new DatabaseHelper(mContext);
}

public DataBaseHandler open() throws SQLException {
    mDb = mDbHelper.getWritableDatabase();
    return this;
}

public void close() {
    mDbHelper.close();
}

// Insert the image to the Sqlite DB
public void insertImage(byte[] imageBytes) {
    ContentValues cv = new ContentValues();
    cv.put(IMAGE, imageBytes);
    mDb.insert(IMAGES_TABLE, null, cv);
}

// Get the image from SQLite DB
// We will just get the last image we just saved for convenience...
public byte[] retreiveImageFromDB() {
    Cursor cur = mDb.query(true, IMAGES_TABLE, new String[]{IMAGE,},
            null, null, null, null,
            IMAGE_ID + " DESC", "1");
    if (cur.moveToFirst()) {
        byte[] blob = cur.getBlob(cur.getColumnIndex(IMAGE));
        cur.close();
        return blob;
    }
    cur.close();
    return null;
}
}

【问题讨论】:

  • 请改变主意:将图像保存在本地,并且不要用 BLOBS 膨胀您的数据库。仅存储图像路径。
  • 或者,更好的是,甚至不用费心保存图像。只需存储 URL。
  • 我需要能够离线访问图像..因此需要将其保存在数据库中...是的,我确实检查了其他线程,但没有得到我正在寻找的内容对于

标签: java android sqlite android-sqlite sqliteopenhelper


【解决方案1】:

将图像存储在本地数据库中并不是一个好主意,因为光标大小有限制See details 你可以做这样的事情 首先从服务器下载图像并存储在内部存储中,然后将本地路径存储在数据库中

private String saveToInternalStorage(Bitmap bitmapImage){
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
         // path to /data/data/yourapp/app_data/imageDir
        File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
        // Create imageDir
        File mypath=new File(directory,"profile.jpg");

        FileOutputStream fos = null;
        try {           
            fos = new FileOutputStream(mypath);
       // Use the compress method on the BitMap object to write image to the OutputStream
            bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
        } catch (Exception e) {
              e.printStackTrace();
        } finally {
            try {
              fos.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
        } 
        return directory.getAbsolutePath();
    }

使用读取图像

private void loadImageFromStorage(String path)
{

    try {
        File f=new File(path, "profile.jpg");
        Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
            ImageView img=(ImageView)findViewById(R.id.imgPicker);
        img.setImageBitmap(b);
    } 
    catch (FileNotFoundException e) 
    {
        e.printStackTrace();
    }

}

来自https://stackoverflow.com/a/17674787/2941375的参考

【讨论】:

    【解决方案2】:

    当您每次将图像存储在数据库中时,您必须转换为字节,反之亦然。它也可能导致内存异常所以什么 我会建议你,而不是将图像存储在数据库中尝试将该图像的 URL 存储在数据库中,然后从数据库中获取图像的 url 并使用 Picasso 或 Glide 图像库显示图像。

    【讨论】:

    • 我很感激,但我不打算通过互联网实时流式传输图像。考虑到应用程序会在某个时候自动下载图像、保存并离线使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 2015-12-13
    • 2014-01-15
    相关资源
    最近更新 更多