如何在android中的sqlite数据库中插入图像?

时间:2014-02-21 08:00:19

标签: android sqlite

我从网址中检索了一张图片。我想将此图像插入SQLite数据库。 我尝试在编码后插入它,但是存在一个刺痛值。任何人都可以建议如何将图片插入SQLite数据库。这是我的代码:

Login.java

 final String t1=user.getId();
final String t2=user.getName();
AsyncTask<Void, Void, Bitmap> t = new AsyncTask<Void, Void, Bitmap>(){

@Override
    protected Bitmap doInBackground(Void... arg0) {
        // TODO Auto-generated method stub
             Bitmap bm = null;
                   try {
                     URL aURL = new URL("http://graph.facebook.com/"+t1+"/picture?type=small");
                     URLConnection conn = aURL.openConnection();
                     conn.setUseCaches(true);
                     conn.connect(); 
                     InputStream is = conn.getInputStream(); 
                     BufferedInputStream bis = new BufferedInputStream(is); 
                     bm = BitmapFactory.decodeStream(bis);

                     bis.close(); 
                     is.close();
                      } 
                                 catch (IOException e) { 
                             e.printStackTrace(); 
                         }
                         return bm;
                    }
                    protected void onPostExecute(Bitmap bm){
                        //Drawable drawable = new BitmapDrawable(getResources(), bm);
                        Bitmap b1=bm;
                        ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
                        b1.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                        byte[] b = baos.toByteArray();  
                        // Log.w("bit",""+drawable);
                         String encodedImage = Base64.encodeToString(b,Base64.DEFAULT);
                        fbdetails.put("fbname",t2);
                        fbdetails.put("fbuserid",t1);
                        fbdetails.put("fbpic",encodedImage);
                        db.insertme(fbdetails);
                    }
                 };
                 t.execute();
            }
        });

Databasehandler.java

public void insertme(HashMap<String, String> queryValues) {
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put("fbname", queryValues.get("fbname"));
    values.put("fbuserid", queryValues.get("fbuserid"));
    values.put("fbpic", queryValues.get("fbpic"));

    database.insert("me", null, values);
    database.close();
}

6 个答案:

答案 0 :(得分:1)

将图像放入数据库是一种糟糕的做事方式 - 你膨胀数据库b并从中获取数据,然后需要将其转换为正确的格式。而是将其存储到磁盘* (SDCARD) *并将存储它的文件名放入数据库中。然后从 SDCARD加载

答案 1 :(得分:1)

您应该查找BLOB类型信息,这是在您的数据库中存储图像的唯一方法。但是你需要先转换你的位图。

答案 2 :(得分:0)

必须编码base64 String Vist [http://developer.android.com/reference/android/util/Base64.html]

答案 3 :(得分:0)

您只应在数据库中插入图像的路径。

String path = Images.Media.insertImage(context.getContentResolver(), bm, "YourTitle", null);

将路径插入String ...

答案 4 :(得分:0)

public class ImageManipulation {

public static String encodeImage(byte[] imageByteArray) {
return Base64.encodeToString(imageByteArray, 0);
}

public static byte[] decodeImage(String imageDataString) {
return Base64.decode(imageDataString, 0);
}

public static Drawable getDrawableFromString(String imageString) {
byte[] imageBytes = decodeImage(imageString);
Drawable image = null;
image = new BitmapDrawable(BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length));

return image;

}

}

您可以使用上面的util类。

答案 5 :(得分:0)

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class MyDataBase extends SQLiteOpenHelper{

    public MyDataBase(Context context, String dbname, CursorFactory factory, int dbversion) {
        super(context, dbname, factory, dbversion);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table tableimage(image blob);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}


========================================

import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

    private ImageView imageview=null;
    private Button btninsert=null;
    private Button btnretrive=null;
    private MyDataBase mdb=null;
    private SQLiteDatabase db=null;
    private Cursor c=null;
    private byte[] img=null;
    private static final String DATABASE_NAME = "ImageDb.db";
    public static final int DATABASE_VERSION = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btninsert=(Button)findViewById(R.id.button_insert);
        btnretrive= (Button)findViewById(R.id.button_retrieve);
        imageview= (ImageView)findViewById(R.id.imageView_image);
        imageview.setImageResource(0);
        btninsert.setOnClickListener(this);
        btnretrive.setOnClickListener(this);
        mdb=new MyDataBase(getApplicationContext(), DATABASE_NAME,null, DATABASE_VERSION);


        Bitmap b=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        b.compress(Bitmap.CompressFormat.PNG, 100, bos);
        img=bos.toByteArray();
        db=mdb.getWritableDatabase();
    }
    @Override
    public void onClick(View arg0) {

        if(btninsert==arg0)
        {
            ContentValues cv=new ContentValues();
            cv.put("image", img);
            db.insert("tableimage", null, cv);
            Toast.makeText(this, "inserted successfully", Toast.LENGTH_SHORT).show();
        }
        else if(btnretrive==arg0)
        {
                String[] col={"image"};
                c=db.query("tableimage", col, null, null, null, null, null);

                if(c!=null){
                    c.moveToFirst();
                    do{
                        img=c.getBlob(c.getColumnIndex("image"));
                       }while(c.moveToNext());
                }
                Bitmap b1=BitmapFactory.decodeByteArray(img, 0, img.length);

                 imageview.setImageBitmap(b1);
                 Toast.makeText(this, "Retrive successfully", Toast.LENGTH_SHORT).show();
            }
        }

}

你可以使用上面的代码..